2016-04-13 18 views
1

私はちょうど3週間自然に反応し、親の状態に基づいてカスタムコントローラの値を更新するのが難しいです。コードでjs fiddle to react native他のコンポーネントとのネイティブ双方向バインディングに反応する

、私はカスタムコントロール入力から入力したときに、親の入力が更新されました:ここ

はフィドルです。しかし、親入力から入力すると、カスタムコントロール入力は更新されません。

私の間違いを指摘できますか?

はまた、ここに私のコードです:

var React = require('react-native'); 
var { 
    AppRegistry, 
    StyleSheet, 
    Text, 
    View, 
    TextInput 
} = React; 

var CustomControl = React.createClass({ 
    propTypes: { 
     onChangeTextValue: React.PropTypes.func, 
     value: React.PropTypes.string.isRequired 
    }, 

    getDefaultProps: function() { 
     return { 
      onChangeTextValue:() => { }, 
      value: "" 
     } 
    }, 

getInitialState: function() { 
    return { 
     text: this.props.value 
    }; 
}, 

setText: function(value) { 
    this.setState({ 
     text: value 
    }); 
    try { 
     return this.props.onChangeTextValue(value); 
    } catch (_error) { } 
}, 

render: function(){ 
    return (
     <TextInput 
      style={{ height: 40, borderColor: 'gray', 
        borderWidth: 1 }} 
      onChangeText={this.setText} 
      value={this.state.text} 
      /> 
     ) 
    } 
}); 

var SampleApp = React.createClass({ 
    getInitialState() { 
     return { 
      'textValue': '' 
     } 
    }, 
    render: function() { 
     return (
      <View style={styles.container}> 
       <Text> 
        Parent Input 
       </Text> 
       <TextInput 
     style={{height: 40, borderColor: 'gray', borderWidth: 1}} 
     onChangeText={(text) => this.setState({textValue:text})} 
     value={this.state.textValue} 
       /> 
       <Text> 
        Custom control input 
       </Text> 

       <CustomControl 
     onChangeTextValue={(text) => this.setState({textValue:text})} 
       value={this.state.textValue} 
       /> 

       <Text style={styles.instructions}> 
        Updating the parent input should update the custom control value too. Right now only when we update the custom control value, the parent input is updated. 
       </Text> 

      </View> 
     ); 
    } 
}); 

ありがとうございました:)あなたがすべきではない、あなたの子コンポーネントの状態を保存している

答えて

1

、親コンポーネントは、あなたがすべきハンドラをonChangeTextValue渡します代わりに使用してください。

var CustomControl = React.createClass({ 
    propTypes: { 
     onChangeTextValue: React.PropTypes.func, 
     value: React.PropTypes.string.isRequired 
    }, 

    render: function(){ 
     return (
      <TextInput 
       style={{ height: 40, borderColor: 'gray', 
         borderWidth: 1 }} 
       onChangeText={this.props.onChangeTextValue} 
       value={this.props.value} 
       /> 
      ) 
     } 
}); 
+0

ありがとう、あなたの子コンポーネントの代わりにお試しください!これは私が必要とするものです。 :) – prinnny

関連する問題