如何识别由同一父组件呈现的相同类型的每个子组件

时间:2019-05-10 20:03:52

标签: reactjs components

我对React很陌生,我无法弄清楚如何区分相同类型的2个不同子组件。

就我而言,我正在尝试构建一个应用程序,以比较过去5年中两种不同车型的价格。

我有2个SelecComponent,在数据库中有汽车制造商作为选项,还有2个SelecComponent,我需要在数据库中列出每个选定汽车制造商的可用汽车型号,因此前2个SC中的每个SC仅应控制存储了汽车模型的2个SC之一。

通常我会通过不同的ID来识别SelecComponent,并使用jQuery操作它们,但是在React中做到这一点的最佳方法是什么?

父项:

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      carProducers: [],
      carModels: [],
      selectedProducer: null,
      selectedModel: null
    }
  }


  //function to retrieve the carmakers in order to initialize the drop down elements in the page
  componentDidMount(){
    axios.get("/AutoExposed/API/carmakers.php")
    .then(response => {
      var data = response.data
      this.setState({
        carProducers: parseCarProducers(data)
      })
    })
    .catch(error => {
      console.log(error)
    })
  }

  //function to retrieve the car models once the car producer has been selected
  carProducerSelected1 = (selectedValue) =>{
    this.setState({selectedProducer: selectedValue}, () =>{
      axios.get("/AutoExposed/API/carmodels_GET.php?carmaker=" + this.state.selectedProducer.value)
      .then(response => {
        var data = response.data
        this.setState({
          carModels: parseCarModels(data)
        }) 
      })
      .catch(error => {
        console.log(error)
      })
    })   
  }

  carModelSelected = (selectedValue) => {
    this.setState({selectedModel: selectedValue}, ()=>{
      console.log(`The car model has just been selected: `, this.state.selectedModel.value)
    })
  }

  render(){
    return (
      <div className="App">
        <div className="container">
          <div className="row">
            <div className="col-lg-3 col-md-6 col-sm-12 col-sm-12">
            </div>
            <div className="col-lg-3 col-md-6 col-sm-12 col-sm-12">
              <SelectComponent selectOptions={this.state.carProducers} onOptionSelected={this.carProducerSelected}/>
            </div>
            <div className="col-lg-3 col-md-6 col-sm-12 col-sm-12">
              <SelectComponent selectOptions={this.state.carProducers} onOptionSelected={this.carProducerSelected}/>
            </div>
            <div className="col-lg-3 col-md-6 col-sm-12 col-sm-12">

            </div>
          </div>

          <div className="row">
            <div className="col-lg-3 col-md-6 col-sm-12 col-sm-12">

            </div>
            <div className="col-lg-3 col-md-6 col-sm-12 col-sm-12">
            <SelectComponent selectOptions={this.state.carModels} onOptionSelected={this.carModelSelected}/>
            </div>
            <div className="col-lg-3 col-md-6 col-sm-12 col-sm-12">
              <SelectComponent selectOptions={this.state.carModels} onOptionSelected={this.carModelSelected}/>
            </div>
            <div className="col-lg-3 col-md-6 col-sm-12 col-sm-12">

            </div>
          </div>

          <div className="row">
            <div className="col-lg-9 col-md-9 col-sm-12 col-sm-12">
              <ChartComp />
            </div>
          </div>
        </div>





      </div>
    );
  }

}

export default App;

子组件:

class SelectComponent扩展了Component {     状态= {         selectedOtptionState:null,     }

optionWasSelected = (selectedOption) => {

    this.setState({selectedOtptionState: selectedOption}, () => {
        this.props.onOptionSelected(this.state.selectedOtptionState)
    })
}

render() {
    return (
        <Select 
            value={this.state.selectedOtptionState}
            onChange={this.optionWasSelected}
            options = {this.props.selectOptions} 
        /> 

    );
}

} 导出默认的SelectComponent;

2 个答案:

答案 0 :(得分:0)

您需要将数据取回数组中,然后需要对其进行映射,并且对于数组中的每个迭代(对象),请为其提供一个组件。并在组件中将当前迭代(将当前项目的信息传播到组件props对象)传递给它,并将其显示在组件中。

apiData.map(item,index)=>{ return <CarComponent {...item} key={index}/>})

现在您已经将当前汽车的所有信息都传递给了道具,您可以显示该信息

const CarComponet=props => {

      return (
          <div>

            <h1>{props.title} </h1>
              <p>{props.carMake} </p>
              <p>{props.carYear} </p>
              <p>{props.carPrice} </p>
         </div>

             )

}

答案 1 :(得分:0)

您在正确的方向上进行了设置。这里的区别是思维过程有所改变-使用jQuery之类的东西,您可以将事件基于ID连接到元素,然后通过事件直接更新它们,就像在反应时将事件处理程序连接到渲染然后更新状态一样当事件触发后又以新状态重新呈现;

首先-由于您有两种不同的汽车/生产者,因此您将需要每个状态变量来存储两种不同的值及其模型(例如selectedMainProducerselectedCompareProducermainCarModels,{ {1}})。同样,在这种情况下,最好有单独的事件处理程序来区分使用哪个选择并设置适当的状态:

compareCarModels

然后在您的状态下存储两个不同的值及其模型,例如:

<SelectComponent onOptionSelected={this.onMainProducerSelected} ... />
...
<SelectComponent onOptionSelected={this.onCompareProducerSelected} ... />
...

使用此方法,然后根据onMainProducerSelected = (selectedValue) => { this.setState({ selectedMainProducer: selectedValue, },() => { axios.get(api + this.state.selectedMainProducer.value).then(response => { var data = response.data this.setState({ mainCarModels: parseCarModels(data), // <-- separate models }); }); }); } onCompareProducerSelected = (selectedValue) => { this.setState({ selectedCompareProducer: selectedValue, },() => { axios.get(api + this.state.selectedCompareProducer.value).then(response => { var data = response.data this.setState({ compareCarModels: parseCarModels(data), // <-- separate models }); }); }); } selectedMainProducer状态呈现辅助选择。

例如

selectedCompareProducer