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

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

    In Filter Component

    handleChange = (event) => {
        if(typeof this.props.selectedValueHandler !== 'undefined'){
            this.props.selectedValueHandler(event.target.value);
        }
    }
    

    In Main Component

    In you main file you need to pass a function selectedValueHandler as a prop to the filtercomponent, which will be used as a callback filtercomponent from inside the Filter component on selection.

    The selected value then can be passed to Data Componennt

    constructor() {
        this.state = {
            selectedValue: null
        }
    }
    
    selectedValueHandler = (selectedValue) => {
        this.setState({
            selectedValue
        })
    }
    
    render() {
            const { selectedValue } = this.state;
            return (
                
    ); }

    In your Data Component

    You can directly access the selected value in Data Component using

    class DataComponent extends Component {
        render() {
            const { selectedValue } = this.props;
            ...
        }
    }
    

    or if you want to make it part of Data Component State.

    class DataComponent extends Component {
    
        constructor(props) {
            super(props);
            this.state = { 
                items: [],
                content: [],
                selectedValue: this.props.selectedValue
            }
        } 
    
        componentwillreceiveprops(nextProps) {
            if(this.state.selectedValue !== nextProps.selectedValue) {
                this.setState({
                    selectedValue: nextProps.selectedValue
                })
            }
    
        }
    
        render() {
            const { selectedValue } = this.state;
            ...
        }
    }
    

    Depends on your use case.

提交回复
热议问题