【问题标题】:unable to assign value dynamically to TextInput using react native无法使用本机反应动态地为 TextInput 赋值
【发布时间】:2015-10-27 05:18:15
【问题描述】:

在我的场景中,当专注于 TextInput 时,我正在使用导航器(使用推送)移动到另一个场景,在那里我填充列表,在该列表中选择一个值,该值应该填充到 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
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    首先,如果你只是传递从组件返回的默认属性,你就不需要再使用绑定了。

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

    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>)
      }
    });
    

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

    希望对您有所帮助。

    【讨论】:

    • thnks eyal83.in my case popBackAndUpdate 函数在组件之外我怎样才能得到FirstComponent这个
    • 对不起,我不明白这个问题。你能解释一下吗?
    • 好的。如何在组件外定义 popBackAndUpdate 函数。
    • 您可能不想这样做。您应该在组件中保留一个真正“面向 React”的功能。您希望您的“this”明确表示它是 React 组件。如果您需要在多个地方重用它,您可以创建一个 mixin 并将其包含在您的不同组件中。
    • 在我的情况下 mixin(因为我是 reactnative 的新手)不适合。是不是不能在组件外定义popBackAndUpdate函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多