首先,我是reactjs的新手。如何在网页上打印选择项?这段代码在控制台中打印输出,但是我想在网页屏幕上打印输出。我该怎么办?
´´´
import React from 'react';
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
console.log('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} 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>
<input type="submit" value="Submit" />
</form>
);
}
}
export default FlavorForm
´´´
答案 0 :(得分:0)
只需添加绑定到“ value”属性的html元素,如下所示:
render() {
return (
<div>
<h3>Flavor: {this.state.value}</h3>
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} 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>
<input type="submit" value="Submit" />
</form>
</div>
);
}
答案 1 :(得分:0)
不确定所需的确切行为,但可以保留一个布尔值,以显示/隐藏文本的状态:
import React from 'react';
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'coconut',
showFlavor: false // this controls whether or not the text is shown
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
// console.log('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
this.setState({ showFlavor: true }); // toggle on our boolean, note that in this example it never gets set back to false
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} 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>
<input type="submit" value="Submit" />
// text appears here only when state.showFlavor is true
<span>{this.state.showFlavor ? `Your favorite flavor is: ${this.state.value}` : ''}</span>
</form>
);
}
}