How to pass data from one component to another component in onchange using React js

前端 未结 3 472
攒了一身酷
攒了一身酷 2021-01-28 22:30

I have two component 1. Filter and 2.Data

I have injected both components in main.js file

1.Main.js

render() {
        return (
            


        
3条回答
  •  野性不改
    2021-01-28 23:08

    My first instinct is to say that you should simply combine the two components into one.

    Components have the ability to carry state for a reason. There's not much point using a functional component and then splitting it's state into a separate component.

    Having content.push in your render function also is a bit weird to do for React. Your render function should be solely responsible for rendering, nothing else. If you want to do something in your render function, make a handler.

    Here's how I'd build your filter class, bear in mind this code is written without being tested so it may require some tweaks, but the general structure is all there.

    import React from 'react'
    
    export default class Filter extends React.Component {
      constructor (props) {
        super(props)
    
        this.state = {
          items: [],
          content: [],
          isLoaded: false,
          error: null,
          selectedColorFilter: null,
          selectedClassFilter: null
        }
    
        //There's probably a better way to refactor this so it's just one handler, but I'm just using two for illustrative purposes here.
        this.handleColorFilterChange = this.handleColorFilterChange.bind(this)
        this.handleClassFilterChange = this.handleClassFilterChange.bind(this)
      }
    
      componentDidMount () {
        fetch('url')
          .then((res) => {
            return res.json()
          })
          .then((data) => {
            this.setState({
              isLoaded: true,
              items: data
            })
          })
          .catch((error) => {
            this.setState({
              isLoaded: false,
              error: error
            })
          })
      }
    
      handleColorFilterChange (event) {
        //this may not be right, but I think it'll pick up the right value, may have to change it
        this.state.selectedColorFilter = event.target.value
      }
    
      handleClassFilterChange (event) {
        //again, might not be right, but I think it'll grab the value
        this.state.selectedClassFilter = event.target.value
      }
    
      renderColorFilter () {
        
  • } renderClassFilter () {
  • } render () { return (
      {this.renderColorFilter()} {this.renderClassFilter()}
    ) } }

    Hope this makes sense.

提交回复
热议问题