我有一个父组件,它可以控制所有状态和一个子组件,该状态和一个子组件返回下拉菜单并通过(应该通过)(应该通过),而不是单击一个选项到parent parent component的结果并更新父母的状态。
父母:
// We're controlling all of our state here and using children
// components only to return lists and handle AJAX calls.
import React, { Component } from 'react';
import SubList from './SubList';
import StopList from './StopList';
class SubCheck extends Component {
constructor (props) {
super(props);
this.state = {
selectedSub: null,
selectedStop: null,
stops: [],
};
this.handleSubSelect.bind(this);
this.handleStopSelect.bind(this);
}
// We want the user to be able to select their specific subway
// stop, so obviously a different array of stops needs to be
// loaded for each subway. We're getting those from utils/stops.json.
handleSubSelect(event) {
var stopData = require('../utils/stops');
var stopsArray = [];
for (var i = 0; i < stopData.length; i++) {
var stop = stopData[i];
if (stop.stop_id.charAt(0) == event.target.onSubSelect) {
stopsArray.push(stop.stop_name);
}
}
this.setState(() => {
console.log('setting state');
return {
selectedSub: event.target.onSubSelect,
stops: stopsArray
}
});
}
handleStopSelect(event) {
this.setState({selectedStop: event.target.onStopSelect});
}
render() {
return (
<div>
<SubList onSubSelect={this.handleSubSelect.bind(this)}/>
<StopList stops={this.state.stops} onStopSelect={this.handleStopSelect.bind(this)}/>
</div>
);
}
}
export default SubCheck;
儿童:
import React from 'react';
import PropTypes from 'prop-types';
function SubList (props) {
const subways = ['', '1', '2', '3', '4', '5', '6',
'S', 'C', 'B', 'D', 'N', 'Q', 'R', 'L']
return (
<select>
{
subways.map(subway =>
<option key={subway} onClick={() => props.onSubSelect(subway)}>
{subway}
</option>
)
}
</select>
)
}
SubList.PropTypes = {
onSubSelect: React.PropTypes.func.isRequired
};
export default SubList;
当我按原样打开应用程序并从下拉菜单中选择一个选项时,我期望发生的两件事不会发生。一个是第二个菜单(由Soplist返回的菜单,此处不包含的代码)没有填充任何数据。第二件事是"设置状态"未登录到控制台。第二件事使我相信我的代码中的某个地方,我没有正确地将下拉中的选项单击到我的handlesubselect方法,因此无法正确设置任何新状态。
您需要在SELECT元素上使用Onchange处理程序:
<select onChange={props.onSubSelect}>
您的OnSubSelect处理程序将收到一个事件,您需要从event.target.value。
获得所选值。请参阅文档:
https://facebook.github.io/react/docs/forms.html#the-select-tag
您应该将方法绑定为:
this.handleStopSelect = this.handleStopSelect.bind(this);
如这里。当然,将元素更改为以下内容:
<SubList onSubSelect={this.handleSubSelect}/>
也代替 event.target.onbelect 您可以尝试 event.target.value
您已经完成了绑定,因此您不需要,实际上,当用户更改选择时,您所做的所有选择是在执行bind
所以更改此行
<SubList onSubSelect={this.handleSubSelect.bind(this)}/>
到这个
<SubList onSubSelect={this.handleSubSelect}/>
世界应该更快乐。
您有onStopSelect
update
在handleSubSelect()
方法中,您要这样做:
this.setState(() => {
console.log('setting state');
return {
selectedSub: event.target.onSubSelect,
stops: stopsArray
}
});
看起来有些混乱,我认为应该是这样的:
console.log('setting state');
this.setState({
selectedSub: event.target.onSubSelect,
stops: stopsArray
}
);