You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击图标添加TextInput组件失效,求React Native解决方案

Fix: Adding TextInput on Icon Click in React Native

Hey there! Let's get that "add answer" functionality working properly. The issue with your current code is that you're modifying state directly (which React doesn't like) and relying on an unnecessary answerLength state variable—here's how to fix it:

What Went Wrong?

  • You can't directly mutate this.state.answers.length and expect React to re-render. React detects state changes by comparing references, not just property values. Mutating the array directly won't trigger an update.
  • The answerLength state is redundant; you can always get the count from this.state.answers.length instead of tracking it separately.

Updated Working Code

class CreateSurvey extends Component {
  constructor(props) {
    super(props);
    // Initialize state with just the answers array
    this.state = { 
      answers: [{ answer: '' }]
    };
  }

  optionCount() {
    // Use the functional form of setState to ensure we have the latest state
    this.setState(prevState => ({
      // Create a new array with existing answers + a new empty answer object
      answers: [...prevState.answers, { answer: '' }]
    }));
  }

  render() {
    return (
      <View>
        <View>
          {this.state.answers.map((answer, index) => (
            <TextInput
              key={index}
              placeholder='Add answer variant'
              value={answer.answer}
              // Add onChangeText to update the input value in state
              onChangeText={(text) => {
                const updatedAnswers = [...this.state.answers];
                updatedAnswers[index].answer = text;
                this.setState({ answers: updatedAnswers });
              }}
            />
          ))}
        </View>
        <TouchableOpacity onPress={this.optionCount.bind(this)}>
          <EIcon name={'circle-with-plus'} />
        </TouchableOpacity>
      </View>
    );
  }
}

Key Changes Explained

  1. Removed redundant state: Got rid of answerLength since we can use this.state.answers.length whenever we need the count.
  2. Proper state update: In optionCount, we use setState with a function that takes the previous state. We create a new array using the spread operator ([...prevState.answers]) and append a new empty { answer: '' } object. This ensures React detects the state change and re-renders to show the new TextInput.
  3. Added input handling: The onChangeText prop updates the corresponding answer in state when the user types—without this, your TextInputs would be read-only since the value is bound to state but never updated.

Now when you click the plus icon, a new TextInput should appear immediately!

内容的提问来源于stack exchange,提问作者kalyani_jamunkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:42:10