相信各位看官们很熟悉各种Html的Events事件,
这篇呢~我们要透过上一篇所提到的State传入子类别的方式套用再Event上面!
首先,我们先在Component里建立一个function,这个function,小菜鸟很单纯的只改变了一个state的值
class FormController extends React.Component{
constructor(props) {
this.state ={
test:""
}
}
function setTestState(){
this.setState({
test:"1234"
})
}
}
接着,将这个function绑在这个Class上
class FormController extends React.Component{
constructor(props) {
this.state ={
test:""
}
this.setTestState=this.setTestState.bind(this);
}
function setTestState(){
this.setState({
test:"1234"
})
}
}
将function 传入子类别当作prop使用
import Test from '../../TestComponent/Test';
class FormController extends React.Component{
constructor(props) {
this.state ={
test:""
}
this.setTestState=this.setTestState.bind(this);
}
function setTestState(){
this.setState({
test:"1234"
})
}
render(){
return(
<Test
setTestState={this.setTestState}
/>
)
}
}
在子类别透过触发事件来执行父类别传来的 prop function
class Test extends React.Component{
constructor(props) {
}
render(){
const {setTestState} = this.props;
return(
<div>
<input onChange={setTestState}/>
</div>
)
}
}
当然上面是属於最阳春的方式,我们也可以在子类别传入参数给prop function,
进而在父类别拿到子类别传入的参数来作使用。
假设我不想要我的state一直都是1234,我想要自己定义这个state的值
在父类别建立function,且绑定在这个Class上
class FormController extends React.Component{
constructor(props) {
this.state ={
test:""
}
this.setTestState=this.setTestState.bind(this);
}
function setTestState(value){
this.setState({
test:value
})
}
}
接着在子类别传入参数
class Test extends React.Component{
constructor(props) {
}
render(){
const {setTestState} = this.props;
return(
<div>
<input onChange={function(e){setTestState(e.target.valaue)}}/>
</div>
)
}
}
这边作一个小小补充! 就是ES6有一个写法可以预设传入参数的值
class FormController extends React.Component{
constructor(props) {
this.state ={
test:""
}
this.setTestState=this.setTestState.bind(this);
}
function setTestState(value='1234'){
this.setState({
test:value
})
}
}
最後再一个小小提醒 ! 当父类别的State变动时,子类别里的Prop会重新渲染
这边小菜鸟说明了如何将父类别function传入子类别,变成prop来襄在事件上面。
下一篇,我们要来说明React的一个外部套件 => Prop Types
PropTypes 简单来说,就是拿来检查 prop的型别及是否是必要传入的prop
希望看到这边,各位看官们还没有要睡着的迹象 ( ・ั﹏・ั)
<<: 零信任原则(Zero Trust principles)
SharedPreferences SharedPreferences可以做到储存简单资料的功能,简...
GitHub Issue 有点像是专案管理系统内管理工作事项的功能,但它能达到功能更多:无论是个人或...
▉估狗『各国 个资法』 就~如标题,既昨天的笔记,想看看,那各国的个资法是?? 然後就看到这个『隐私...
前言 这篇文章超级适合给manager们,特别是那些非常重视团队成员成长的领导人们。或许你曾经尝试...
今天的内容为该如何简单制作出一个自动攻击的敌人 ...