【问题标题】:React Native | How to create dynamic state(hook)?反应原生 |如何创建动态状态(钩子)?
【发布时间】:2020-11-03 06:40:47
【问题描述】:

如果提供了控制,我必须生成一个文本输入。我需要将状态放入 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")}
             />
)}
})

【问题讨论】:

  • 列表是状态的一部分吗?
  • 部分。根据返回的 item.name 命名。
  • 如果它是一个状态数组,你可以简单地拥有一个 value 属性并根据索引更新它
  • 在此函数之外声明一个空白数组,并在每次迭代中使用该数组。

标签: reactjs react-native react-hooks state


【解决方案1】:

试试这个方法

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 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2020-04-05
    • 2021-10-12
    • 2020-10-23
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    相关资源
    最近更新 更多