【问题标题】:this.setState is not working for multiple text input in react-nativethis.setState 不适用于 react-native 中的多个文本输入
【发布时间】:2018-06-02 19:01:37
【问题描述】:
    {
      element.answers_data.map((answer, index) =>
          <View key={index} style={{paddingLeft: 20}}>
          <TextInput
            value = {answer.answer_text}
             onChangeText={(answer_text) => {
               this.setState({answer_text: answer_text});
             }}
            />
          </View>
    )}

我在数组中使用 TextInput。但它不起作用。请提供任何解决方案。提前致谢

【问题讨论】:

    标签: arrays reactjs react-native react-native-android react-native-ios


    【解决方案1】:

    如果你的文本输入是一个数组,你应该把它的反射 state 也变成一个数组:

    constructor(props) {
        super(props);
        this.state = {
            answers: element.answers_data.map( (answer, index) => {
                return answer.answer_text
            }),
        }
    }
    
    render() {
        return (
            <View>
            {
            element.answers_data.map((answer, index) =>
                <View key={index} style={{paddingLeft: 20}}>
                    <TextInput
                        value = {this.state.answers[index]}
                        onChangeText={(answer_text) => {
                            /// Since state is immutable, construct a new array for modified answer for specific index.
                            this.setState({
                                answers: [
                                    ...this.state.answers.slice(0, index),
                                    answer_text,
                                    ...this.state.answers.slice(index+1, this.state.answers.length)
                                ]
                            });
                        }}
                    />
                </View>
            )
            }
            </View>
        )
    }
    

    由于状态是不可变的,你不能只用索引改变数组值。 检查代码,例如为修改后的answer 构造一个新数组。

    【讨论】:

    • 比您的回复多多益善。它工作正常。我刚刚用 this.state.answers.length 替换了 this.state.answers.length-1 并且它工作正常。
    • 是的,很忙,刚刚找到它。太棒了,你也找到了!更正了我的代码 =)
    【解决方案2】:

    您是否尝试使用多个输入更改同一个状态字段?
    可以分开吗?
    关于不工作,你是什么意思,组件更新但状态没有改变,回调没有调用,你总是得到相同的 answer_text 或其他什么?

    【讨论】:

      猜你喜欢
      • 2020-08-26
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 2018-04-16
      相关资源
      最近更新 更多