无法使用react native动态地为TextInput赋值

时间:2015-10-27 05:18:16

标签: react-native

在我的场景中,当我关注TextInput时,我正在使用导航器(使用push)移动到另一个场景,我填充列表,在该列表中选择一个值,该值应该填充到TextInput的前一个场景。在这种情况下,我是无法将所选值设置为TextInput的上一个场景。

我的代码结构是

var FirstComponent = React.createClass({
     render:function(){
             return(<TextInput value="" placeholder="Enter value" onFocus={getData.bind(this)} />)
      }
})

function getData(ev){
var target = ev;
      this.props.navigator.push({
          id:'SecondComponent',
          name:'SecondComponent',
          target:target, 
       })
}
var SecondComponent = React.createClass({
        render:function(){
               return(<TouchableHighlight onPress={fillData.bind(this,target, self.props.navigator,selectedText)}><Text>sample</Text></TouchableHighlight>)
        }
});
function fillData(rootThis,nav,selectedText,ev){

     rootThis.value=selectedText;
     rootThis.nativeEvent.target = selectedText;
     rootThis.nativeEvent.target .text= selectedText; // Here ' rootThis ' is route object 'this'

//how to fill selectedText in FirstComponent TextInput value
}

1 个答案:

答案 0 :(得分:1)

首先,如果您只是传递从组件返回的默认属性,则不需要再使用bind。

无论如何,我会做这样的事情:

first_component.js:


var FirstComponent = React.createClass({
  getInitialState: function() {
    value: ""
  },

  render:function(){
    return(
      <TextInput value={this.state.value} placeholder="Enter value" onFocus={this.moveToSecondComponent} >
    );
  },

  moveToSecondComponent: function() {
    this.props.navigator.push({
      component: SecondComponent
      onSelect: this.popBackAndUpdate // This assumes you are using Navigator. If you are using NavigatorIOS, just wrap it in 'passprops'
    })
  },

  popBackAndUpdate: function(value) {
    this.setState({value: value});
    this.props.navigator.pop();
  }

});


second_component.js:
var SecondComponent = React.createClass({
  render: function() {
    return(
      <TouchableHighlight onPress={() => { this.props.route.onSelect("new value")}}>
        <Text>sample</Text>
      </TouchableHighlight>)
  }
});

这个要点是,在第二个组件中,您只需将新值传递给回调函数,它将弹出导航器。

希望有所帮助。