2016-04-13 56 views
1

我剛剛學習反應原生三個星期,我很難根據父狀態更新自定義控制器值。反應本機雙向綁定與另一個組件

這裏是小提琴: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