添加对自定义组件的引用

时间:2017-02-27 15:54:16

标签: react-native

参考react-native-elements库并使用其复选框组件。

  constructor(props) {
  super(props);
  this.state = {
       checked: true
       titleText1:"Checkbox one"
       titleText1:"Checkbox two"
     }
   }
  render() 
  {
     return (
            <View>
  <CheckBox ref='chk1' checked={this.state.checked} title={this.state.titleText1}  />
  <CheckBox ref='chk2' checked={this.state.checked} title={this.state.titleText2}   onPress={this.manageChkboxes()} />
             </View> );
 }

  manageChkboxes(){
  this.state.checked=false
  this.state.titleText1="Checkbox one updated"
  this.state.titleText2= "Checkbox two updated"
    this.refs.chk1.checked= this.state.checked;
    this.refs.chk1.title= this.state.titleText1;
    this.refs.chk2.checked= this.state.checked;
    this.refs.chk2.title= this.state.titleText2;
  }

我无法通过引用来修改组件属性。在调用manageChkboxes()函数时,它会给出错误:null is not an object(evaluating 'this.refs.chk1.checked=!1')

1 个答案:

答案 0 :(得分:1)

如果你想访问道具,你必须稍微改变一下。但是你也不应该为refs使用字符串,也不要直接改变状态,总是使用setState:

  constructor(props) {
  super(props);
  this.state = {
       checked: true
       titleText1:"Checkbox one"
       titleText1:"Checkbox two"
     }
   }

  manageChkboxes(){
  this.setState({
    checked: false,
    titleText1: "Checkbox one updated"
  )};
  }

render(){
  return(
    <View>
      <CheckBox checked={this.state.checked} title={this.state.titleText1}  />
      <CheckBox checked={this.state.checked} title={this.state.titleText2}   onPress={this.manageChkboxes()} />
    </View>
  )
}