我有一个多选字段,根据选择的内容显示/隐藏各种。它们的值等于它们各自的类。
需要帮助转换下面的Jquery代码以反应显示/隐藏适当的s
***** HTML *****
<select id="my_fields" name="my_fields" multiple="multiple">
<option value="gas">Gas</option>
<option value="car_wash">Car Wash</option>
<option value="parking">Parking</option>
<option value="other">Other</option>
</select>
<div class="gas hide">show/hide gas</div>
<div class="car_wash hide">show/hide car_wash</div>
<div class="parking hide">show/hide parking</div>
<div class="other hide">show/hide other</div>
***** JQuery *****
$( "#my_fields" ).change(function () {
$( "#my_fields option:selected" ).each(function() {
$( "."+ $(this).val() ).show();
});
$( "#my_fields option:not(:selected)" ).each(function() {
$( "."+ $(this).val() ).hide();
});
});
*****反应*****
.....imports and class.....
constructor(props) {
super(props);
this.state = {
value: "",
show:false,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
value: event.target.value,
show: true
})
}
render() {
var show = {
display: this.state.show ? "block" : "none"
};
return (
<select
name="my_fields"
multiple
value={this.state.value}
onChange={this.handleChange}
>
<option value="gas">Gas</option>
<option value="car_wash">Car Wash</option>
<option value="parking">Parking</option>
<option value="other">Other</option>
</select>
<div class="gas" style={ show }>show/hide gas</div>
<div class="car_wash" style={ show }>show/hide car_wash</div>
<div class="parking" style={ show }>show/hide parking</div>
<div class="other" style={ show }>show/hide other</div>
)
尝试使用一些修改 -
state = {
values: []
};
handleChange = event => {
const options = Array.from(event.target.options);
const selectedOptions = options.filter(op => op.selected);
const selectedValues = selectedOptions.map(op => op.value);
this.setState({ values: selectedValues });
}
改变你的return
JSX
...
{this.state.values.includes('gas') && <div class="gas">show/hide gas</div>}
{this.state.values.includes('car_wash') && <div class="car_wash">show/hide car_wash</div>}
{this.state.values.includes('parking') && <div class="parking">show/hide parking</div>}
{this.state.values.includes('other') && <div class="other">show/hide other</div>}
handleChange(event) {
var options = event.target.selectedOptions;
var value = [];
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
value.push(options[i].value);
}
}
this.setState({
expenseCategory:[].slice.call(event.target.selectedOptions).map(o => {
return o.value;
})
});
}