首页 > 解决方案 > 反应原生 | 如何创建动态状态(钩子)?

问题描述

如果提供了控制,我必须生成一个文本输入。我需要将状态放入 value 和 onChange 中。所以我必须产生一个动态的状态。我该怎么做呢?

list.map(item =>{
//control true. i need creat textinput
if (control) {
       //I have to create the state here (ex. const[item.name, `set${item.name}`]=useState())
       return(
             <TextInput
                  onChangeText={(text) => ?}
                  value={?}
                  placeholder={item.name}
                  keyboardType={(item.input_type === "tel")}
             />
)}
})

标签: reactjsreact-nativereact-hooksstate

解决方案


试试这个方法

constructor(props){
    super(props);
    this.state = {
      textInput : [],
      inputData : []
    }
  }

onTextChanged = (index, value) => {
    const inputData = [...this.state.inputData]; 
    inputData[index] = value;
}

const textInput = [...this.state.textInput];
    
list.map((item,index) =>{
  //control true. i need creat textinput
  if (control) {
  
    textInput.push(
    <TextInput
      value={this.state.inputData[index] || ''}
          placeholder={item.name}
          onChangeText={(text) => this.onTextChanged(index, text)} 
    />
    );
  }

});


 this.setState({ textInput });

推荐阅读