编辑: 我通过从列表中获取target.value并将其传递给 firstComp.js 来使其工作。 onChange方法如下所示,但这是最佳做法吗?
onchange = (e) =>{
let name= e.target.value
let currentName= this.state.foodData.map((item)=>{
if(name==item.name){
console.log(item)
}
})
}
我正在做stephen griders课程的反应,并尝试实施他在个人项目中教授的内容,但我无法绕过它。
我有一个列表,即循环遍历一个对象数组。当我从该列表中选择一些东西时,我希望它用该对象更新状态。
布局..
DropDownList.js =返回包含foodData中所有成分名称的下拉列表
DropDownItem =遍历foodData,为每个返回一个选项值。
foodData .js = db看起来像这样..
let foodData=[
{"name":"MCT Oil", "brand":"Keppi Keto", "servings":1}
{"name":"Chunky Peanut Butter", "brand":"Skippy"}
]
firstComp.js
import React, { Component} from 'react'
import ReactDOM from 'react-dom'
import foodData from './food/foodData.js'
import DropDownList from './DropDownList.js'
class Layout extends Component {
constructor () {
super()
this.state = {
foodData:foodData,
selectedFood:''
}
this.onchange =this.onchange.bind(this)
}
onchange = (e) =>{
console.log(e.target.value)
}
render () {
return (<div className='home'>
<DropDownList foodData={this.state.foodData} onchange={this.onchange} />
</div>)
}
}
const app = document.getElementById('app')
ReactDOM.render(<Layout />, app)
DropDownList.js
import React from 'react'
import DropDownItem from './DropDownItem.js'
const DropDownList = (props) =>{
****let textInput = React.createRef();**** //REFS
const ingredientItems = props.foodData.map((ingredient, i)=>{
return<DropDownItem key={i} ingredient={ingredient} **ref={textInput}**//REFS />
})
return(
<select value={ingredientItems.name} onChange ={ (e) => props.onchange(e)} >
{ingredientItems}
</select>
)
}
export default DropDownList;
DropDownItem.js
import React from 'react'
const DropDownItem = ({ingredient}) =>{
const itemName = ingredient.name
return(<option value={itemName}>{itemName}</option> )
}
export default DropDownItem;
答案 0 :(得分:1)
您不需要在这里使用refs。您可以在DropdownList组件中使用某种handleChange函数,并将值发送回父组件。
const DropDownList = (props) => {
const handleChange = e => props.onchange( e.target.value );
const ingredientItems = props.foodData.map((ingredient) =>
<DropDownItem key={ingredient.name} ingredient={ingredient} /> );
return (
<select onChange={handleChange}>
{ingredientItems}
</select>
)
}
并在父组件中:
class Layout extends Component {
state = {
foodData,
selectedFood: foodData[0]
};
onchange = name =>
this.setState({
selectedFood: foodData.filter(food => food.name === name)[0]
});
render() {
return (<div className='home'>
<DropDownList foodData={this.state.foodData} onchange={this.onchange} />
</div>)
}
}
或者没有挣扎于值和过滤器,我们可以使用e.target.options.selectedIndex
,因为OP发现他/她自己:)这是一种更干净的方式并且可以作为这个(仅相关部分):
<强> DropdownList.js 强>
const handleChange = e => props.onchange( e.target.options.selectedIndex);
<强> Layout.js 强>
onchange = index => this.setState({ selectedFood: foodData[index] });