如何在Reactjs中将状态值从一个类传递到另一个类

时间:2018-08-01 09:25:52

标签: reactjs typescript

我想将状态值从reactjs中的一个组件传递到另一个组件。如您所见,我正在尝试将价值投入。值在一个组件中声明,并且必须传递另一个组件。 Showvalue是我声明状态值的组件。我希望它成为输入值

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')
);

2 个答案:

答案 0 :(得分:1)

Element()必须是具有状态的Component,并且值必须存储在较高状态(提升状态)中。 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>);
    }
}

答案 1 :(得分:0)

import Inputs from './InputValue.js'
class Showvalue extends Component{
         constructor(props){
         super(props)
         this.state={
             message1: 'hey'
         }
     this.ImportStateValue=this.ImportStateValue.bind(this) 
     ImportStateValue()={
           return this.state.message1
     }

    render(){
               return(
                       <Input Datalink={this.ImportStateValue}>
               )

    }

}
//InputValue.js
class InputValue extends Component{
   constructor(){
      super()
      this.state{
          message2: null;
      }
      this.SetValue=this.SetValue.bind(this)

   }
    async SetValue(){
    await const val=this.props.Datalink()
    this.setState({
        message2: val
    })
 }

 render(){
             return(
                    <button onClick={this.SetValue}></button>
             )
 }

}

首先,您必须初始化ShowValue类中的所有状态值。然后编写一个函数,该函数返回状态值并将该函数使用prop传递给InputValue类。并将该道具分配给Inputvalue类的变量。然后使用Setstate将该变量值分配为您的状态值。您可以使用consol.log(this.state)

测试值
相关问题