点击图标添加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.lengthand 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
answerLengthstate is redundant; you can always get the count fromthis.state.answers.lengthinstead 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
- Removed redundant state: Got rid of
answerLengthsince we can usethis.state.answers.lengthwhenever we need the count. - Proper state update: In
optionCount, we usesetStatewith 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. - Added input handling: The
onChangeTextprop 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
相关产品推荐
相关产品推荐

