简体   繁体   English

反应,遍历对象,显示列表,并在选定对象时抓取该对象

[英]React, looping through object, displaying list, and grabbing that object when selected

Edit: I have made it work by getting the target.value from the list, passing that to firstComp.js . 编辑:我已经通过从列表中获取target.value并将其传递给firstComp.js使其工作 Where the onChange method is below, but is this the best practice? 下面是onChange方法,但这是最佳实践吗?

 onchange = (e) =>{
    let name= e.target.value
    let currentName= this.state.foodData.map((item)=>{
    if(name==item.name){
      console.log(item)
    }
})
}

Im doing stephen griders course on react, and trying to implement what he teaches on a personal project, but I cant wrap my head around it. 我在做斯蒂芬·格里瑟斯课程时会做出反应,并尝试实现他在个人项目中教的内容,但我无法全神贯注。

I have a list, that is looping through an array of objects. 我有一个列表,遍历对象数组。 When I pick something from that list, I want it to update the state with that object. 当我从该列表中选择某项时,我希望它使用该对象更新状态。

The Layout.. 布局..

DropDownList.js = return a drop down list with all the ingredient names in foodData DropDownList.js =返回一个包含foodData中所有成分名称的下拉列表

DropDownItem = loops through the foodData, returning an option value for each one. DropDownItem =遍历foodData,为每个数据返回一个选项值。

foodData .js = db that looks something like this.. foodData .js = db看起来像这样。

let foodData=[
  {"name":"MCT Oil", "brand":"Keppi Keto", "servings":1}
  {"name":"Chunky Peanut Butter", "brand":"Skippy"}
]

firstComp.js 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 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 DropDownItem.js

import React from 'react'

const DropDownItem = ({ingredient}) =>{
  const itemName = ingredient.name
    return(<option value={itemName}>{itemName}</option> )
  }
export default DropDownItem;

在此处输入图片说明

You don't need to use refs here. 您无需在此处使用引用。 You can use some kind of handleChange function in your DropdownList component and send back the value to parent component. 您可以在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>
  )
}

and in the parent component: 并在父组件中:

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>)
  }
}

or without struggling with values and filter, we can use e.target.options.selectedIndex as OP finds out him/herself :) This is a cleaner way and works as this (only related parts) : 或无需费力地处理值和过滤器,我们可以使用e.target.options.selectedIndex因为OP可以发现他/她自己:)这是一种更简洁的方法,并且可以这样工作(仅相关部分):

DropdownList.js DropdownList.js

const handleChange = e => props.onchange( e.target.options.selectedIndex);

Layout.js Layout.js

onchange = index => this.setState({ selectedFood: foodData[index] });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM