【问题标题】:how to concatenate data from json with "this.props" in react如何在反应中将来自json的数据与“this.props”连接起来
【发布时间】:2019-08-21 00:44:49
【问题描述】:

我正在尝试通过数据 json 动态创建文本字段,当我想为每个字段设置一个值和 onChange 函数时会出现问题。

我尝试使用字符串但我没有工作

值={${this.state}.+ ${textfield.label}}

值={this.state.${textfield.label}}

 this.state = {     
  label1: "",
  label2 : ""     
};

}

{textfields.map((textfield) => {
return(
      <TextField
      key={textfield.label}
      label={textfield.name}
      margin="normal"
      fullWidth
      id={textfield.label}
      required
      value={`${this.state}.`+ `${textfield.label}`}
      onChange={e => this.setState({ `${textfield.label}` : e.target.value })}
      />
      )
  })
}

问题在于 value 和 onChange

我期待 值={this.state.label1} 值={this.state.label2}

onChange={e => this.setState({ label1 : e.target.value })} onChange={e => this.setState({ label2 : e.target.value })}

我得到了 值=[对象对象].label1 value=[object Object].label2

或 value="this.state.label1" 但作为 texfield 中的字符串 value="this.state.label1" 但在 texfield 中作为字符串

onChange 显示语法错误

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你能像这样给它起个名字吗?

    {textfields.map((textfield) => {

    return(
          <TextField
          key={textfield.label}
          label={textfield.name}
          margin="normal"
          fullWidth
          id={textfield.label}
          required
        name={textfield.label}
          value={`${this.state}.`+ `${textfield.label}`}
          onChange={e => this.setState({ `e.target.name` : e.target.value })}
          />
          )
      })
    }
    

    【讨论】:

    • 是的,但是 react 显示解析错误:来自e.target.name的第一个 ` 出现意外标记
    【解决方案2】:

    只需在花括号内使用纯 JavaScript。像这样:

     value={this.state[textfield.label]}
    

    【讨论】:

    • value={this.state[textfield.label]} 和 onChange={e => this.setState({ [textfield.label] : e.target.value })}
    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多