【发布时间】:2018-08-08 21:41:26
【问题描述】:
我使用自己的组件创建了一个动态变化的表单,但我不确定如何从中获取信息,因为 select 标记本身仅存在于子组件中。
我用谷歌搜索,发现我需要使用 refs,但我也不知道该怎么做。我发现的另一个选择是使用
document.getElementsByClassName,但由于某些原因,这显然不是最佳方式。
the parent class where the form exists
import React, {Component} from 'react';
import ChoicePair from'./ChoicePair';
import ChoosingPane from './ChoosingPane';
class AppComponent extends React.Component {
state = {
numChildren: 3
}
render () {
const children = [];
this.subjects = [ {name: 'a', dep: 1}, {name: 'b', dep: 2}, {name: 'c', dep: 1}, {name: 'd', dep: 1}];
for (var i = 0; i < this.state.numChildren; i ++) {
children.push(<ChoicePair key={i} number={i} options = {this.subjects} subjects = {this.subjects}/>);
};
return (
<div>
<form onSubmit={this.handleSubmit}>
<ChoosingPane addChild={this.onAddChild}>
{children}
</ChoosingPane>
<button type = "submit"> Get my perfect schedule </button>
</form>
{ console.log(document.getElementById("kira") + "WOW")
}
</div>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
handleSubmit(event) {
event.preventDefault();
alert("hi!");
}
}
export default AppComponent;
中间组件
import React from 'react';
const ChoosingPane = props => (
<div>
<div id="children-pane">
{props.children}
</div>
<div className="card calculator">
<p><button onClick={props.addChild}>+</button></p>
</div>
</div>
);
export default ChoosingPane;
the leaf class where the select tag exists (1)
从 'react' 导入 React, {Component};
class ChoicePair extends Component {
constructor(props){
super();
console.log("KKKKKKK");
this.state = {
depValue: '-1',
subValue: '-1',
}
this.handleDepChange = this.handleDepChange.bind(this);
this.handleSubChange = this.handleSubChange.bind(this);
this.getNames = this.getNames.bind(this);
}
handleDepChange(event) {
this.setState({depValue: event.target.value});
}
handleSubChange(event) {
this.setState({subValue: event.target.value});
}
getNames(collection)
{
console.log(collection);
if(collection)
return collection.map( (item, i) => {
return <option id="kira" key = {i} value={i} cat = {item}>{item.name}</option>
});
}
render() {
//create filtered options constant
const subjectList = this.props.subjects.filter((subjName) => subjName.dep === Number(this.state.depValue));
console.log(subjectList + "kill me");
return(
<div>
<select name = "Select department" value={this.state.depValue} onChange = {this.handleDepChange}>
<option value = '-1' disabled>Department</option>
{this.getNames(this.props.options)}
</select>
<select name = "Select subject" value={this.state.subValue} onChange = {this.handleSubChange}>
<option value = '-1' disabled>Subject</option>
{this.getNames(subjectList)}
</select>
</div>
)
}
}
export default ChoicePair;
【问题讨论】:
-
请在此处分享用户可以复制和操作的真实代码,而不是代码图片。
-
请在此处发布您的代码。
-
完成。谢谢
标签: javascript reactjs forms