我需要你的帮助!
我正在为我的compagny做一个项目,我应该创建一个可以与React重复的选择字段。所以,当我想保存我的选择时,我有一点问题,如果我刷新页面,默认选项仍然相同(而不是选定的选项)。我的代码是select.js:
import React, { Component, PropTypes } from 'react';
class Select extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(data) {
this.setState({value:data.value});
}
render() {
return (
<label>
<select className="widefat" name={this.props.name} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
);
}
}
export default Select;
我更改了默认值:
When i change the select option
我认为这是因为在select.js中它将值初始化为&#39;&#39;并且不保存选择,但我不知道如何保存选择。
答案 0 :(得分:0)
以下是实现此目的的方法:
Key = SEC03
Key = SEC03
Key = SEC03
更进一步
您可以迭代渲染方法中的循环来实现它,如下所示:
import React, { Component, PropTypes } from 'react';
class Select extends React.Component {
constructor(props) {
super(props);
this.state = { value: props.value }; // can be initialized by <Select value='someValue' />
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<label>
<select className="widefat" value={this.state.value} name={this.props.name} onChange={this.handleChange.bind(this)}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
);
}
}
export default Select;
答案 1 :(得分:0)
目标事件属性返回触发事件的元素。它存储了许多属性,将其打印到控制台,熟悉其功能
import React, { Component } from 'react';
class Select extends Component {
constructor(props) {
super(props);
this.state = { value: '' };
}
handleChange = e => this.setState({ value: e.target.value });
render() {
return (
<label>
<select className="widefat" name={this.props.name} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
);
}
}
export default Select;
答案 2 :(得分:0)
经过长时间的搜索文档和互联网的深度,我找到了答案。我忘了添加&#34; for&#34;为我的标签。我的最终代码是:
import React, { Component, PropTypes } from 'react';
class Select extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: this.props.value});
}
render() {
return (
<label htmlFor={this.props.id}>{this.props.label}
<select defaultValue={this.props.value} id={this.props.id} className="widefat" name={this.props.name} onChange={this.handleChange.bind(this)}>
<option>Aucun</option>
<option value="55">Option 2</option>
<option value="126">Backend configuration & installation</option>
<option value="125">Frontend integration</option>
<option value="124">Graphic Design</option>
</select>
</label>
);
}
}
export default Select;