繁体   English   中英

当我使用 react.js 单击选择时,如何显示三个参数?

[英]How can I do to show three params when I click on the select using react.js?

我有一个选择,例如:

<Select id='1' list={[...this.state.dictionnary]}/>

this.state.dictionnary是这样的:

state = {
        dictionnary: [
            {value: "a", name: "ab"},
        ]}

组件选择是这样的:

class Select extends Component {

    handleChange()
    {
        // I would like to show 1, a and ab
        // 1 is the id of the select
        // a and ab are value and name of 
  };
    render() {
        return (
            <select onChange={this.handleChange} className="custom-select">{this.props.list.map(option => (
                <option key={option.value} value={option.value}>{option.name}</option>))}
            </select>
        )
    }
}

export default Select;

我想使用handleChange()函数显示一些信息,如 id、name 和 value。

请问你能帮帮我吗 ?

非常感谢

您应该更改该选项,以便该值具有整个对象,以便稍后在 handleChange 中获取它。 此外,要使用 handleChange 方法中的道具访问相同的this ,您需要使用箭头函数:

<select onChange={(e) => this.handleChange} className="custom-select">
    {this.props.list.map((option) => (
      <option key={option.value} value={option}>
        {option.name}
      </option>
    ))}
</select>

默认情况下, onChange 处理程序获取事件参数,以便您可以获取目标和道具:

handleChange(event) {
    const { value, name } = event.target.value;
    console.log(this.props.id, value, name);
}

添加到@Alavaro 答案,您需要在将值获取到 remote 后split ,

 handleChange = e => {
    const [value, name] = e.target.value.split(',')
    console.log({ id: this.props.id, value, name})
  }
  render() {
    return (
      <select onChange={this.handleChange} className="custom-select">
        {this.props.list.map((option, index) => (
          <option key={option.value} value={[option.value, option.name]} >
            { option.name }
          </option>
        ))}
      </select>
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM