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

前端 未结 3 429
攒了一身酷
攒了一身酷 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:09

    According to my knowledge, there are 2 way for solving this problem:

    1. Using Redux for controlling the common state of your application. Please see an example in Redux website (https://redux.js.org/basics/exampletodolist)

    2. Using parent's state

    In your Main.js init the state for containing the change in its child Filter

    constructor(props) {
        super(props);
        this.state = { 
            value: null, //used to contains your dropdown value
        }
        this.getDropdownData = this.getDropdownData.bind(this);
    } 
    

    and the function for getting the value from Filter

    getDropdownData(value){
        this.setState({
            value : myvalue
        });
    }
    

    then pass the getDropdownData() function to getting data to Filter and the value in state to Data Component

    render() {
            return (
                
    ); }

    In Filter.js

    Call the passed function in this.handleChange by using this.props.getDropdownData(input_dropdown_value)

    Do not forget to bind this.handleChange in the constructor()

    this.handleChange = this.handleChange.bind(this)
    

    Finally

    Using the drop-down value in DataComponent by calling this.props.dropdownValue

    Hope it can help you

提交回复
热议问题