冰雹。我正在尝试使用http://fipeapi.appspot.com/ API从第一个选择选项中选择第二个选择选项。
例如在第一个选择中,我具有以下选项: 1.水果 2.根 3.花
如果我选择“水果”,则会显示橙色,苹果和草莓 如果我选择“根”,则将出现“甜菜,胡萝卜和萝卜” 如果我选择“花朵”,则会出现朝鲜蓟,花椰菜和西兰花
所以当我选择水果时,我没有得到第一选择的值来显示第二选择的选项
我尝试做一个引用来获取第一个选择的值,但是我没有在第二个选择中使用它。
所有代码: http://jsfiddle.net/Orcrinhos/jfq7zc5p/
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
marks: [],
models: [],
};
this.handleSubmit = this.handleSubmit.bind(this);
this.getMark = this.getMark.bind(this);
this.getModel = this.getModel.bind(this);
}
componentDidMount() {
this.getMarkInfo();
this.getModelInfo();
}
handleSubmit(event) {
event.preventDefault();
alert('test');
}
getMark(event) {
this.getMarkInfo(this.refs.markRef.value)
this.setState({ markValue: event.target.value });
}
getModel(event) {
this.getCarInfo(this.refs.modelRef.value)
this.setState({ modelValue: event.target.value });
}
getMarkInfo() {
const url = `http://fipeapi.appspot.com/api/1/carros/marcas.json`;
fetch(url)
.then(data => data.json())
.then(data => this.setState({ marks: data }));
}
getModelInfo(markRef = this.refs.markRef.value) {
const url = `http://fipeapi.appspot.com/api/1/carros/veiculos/${markRef}.json`;
fetch(url)
.then(data => data.json())
.then(data => this.setState({ models: data }));
}
render() {
return (
<div>
<form>
<fieldset>
<legend>Some legend</legend>
{/* First select */}
<select ref="markRef" onChange={(e) => { this.getMark(); }}>
{this.state.marks.map(function (mark, index) {
return (
<option key={index} value={mark.id}>{mark.name}</option>
)
}
)}
</select>
{/* Second select */}
<select ref="modelRef" onChange={(e) => { this.getModel(); }}>
{this.state.models.map(function (model, index) {
return (
<option key={index} value={model.id}>{model.name}</option>
)
}
)}
</select>
</fieldset>
<button type="submit">Show data</button>
</form>
<h3>Marks of car</h3>
<div className="break">
{this.state.marks.map(function (mark, index) {
return (
<div key={index}>
<p>{mark.name}</p>
</div>
)
}
)}
</div>
<h3>Models of car</h3>
{this.state.models.map(function (model, index) {
return (
<div key={index}>
<p>{model.name}</p>
</div>
)
}
)}
</div>
);
}
}
export default App;
当我尝试其他方式时:
无法读取未定义的属性“目标”
答案 0 :(得分:1)
请在函数中将事件作为参数传递。请尝试以下
{/* First select */}
<select ref="markRef" onChange={(e) => { this.getMark(e); }}> // pass event as e
{this.state.marks.map(function (mark, index) {
return (
<option key={index} value={mark.id}>{mark.name}</option>
)
}
)}
</select>
{/* Second select */}
<select ref="modelRef" onChange={(e) => { this.getModel(e); }}> //pass e
{this.state.models.map(function (model, index) {
return (
<option key={index} value={model.id}>{model.name}</option>
)
}
)}
</select>