首页 > 解决方案 > How to pass state value from one class to another in Reactjs

问题描述

I want to pass state value from one component to another in reactjs. As you can see i am trying to put value into input. Value is declared in one component and has to pass another component. Showvalue is the component where i declare a state values. And i want it into input value

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Showvalue extends Component{
    constructor(props){
        super(props);
        this.state = {
            values: 'dsfg'
        }

    }
    render(){
        return (<div>{this.state.values}</div>);
    }
}
class Showinput extends Component{
    constructor(props){
        super(props);
        this.state = {
            value:this.props.values
        }
    }

    render(){
        return (
            <input value={this.state.value}></input>
        );
    }
}

function Element(){
    return(
        <div>
        <Showvalue />
        <Showinput />
        </div>
    );
}

ReactDOM.render(

    <Element/>,
    document.getElementById('root')
);

标签: reactjstypescript

解决方案


Element() has to be a Component with state and the value has to be stored in upper state (lifted state). IE:

Class Element extends Component{
    constructor(props){
        super(props);
        this.state = {
            value: 'dsfg'
        }

    }
    
    onChange = (val) => this.setState({ value: val })
    
    render(){
        return (<div>
        <Showvalue value={this.state.value} />
        <Showinput value={this.state.value} changeValue={this.onChange}/>
        </div>);
    }
}


推荐阅读