reactjs - 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')
);
解决方案
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>);
}
}
推荐阅读
- facebook-graph-api - Graph API 中的页面缺少连接的 Instagram 帐户字段
- javascript - 如何在 javascript 中使用 map() 从 javascript 对象中提取数据?
- php - 将数组分配给变量改变了类型?
- python - Python - 分数的分类和序列匹配器
- ios - iOS 将图像和文本共享到 UIActivityViewController 然后在 Objective-C 中出现错误
- python-3.6 - 在python中将字符串写入文件时出错
- ios - 可本地化字符串文件可以动态更改吗?
- php - 如何让来自两个不同 php 页面的变量一起显示在第三个 php 页面?
- mysql - Laravel 4 迁移无法添加外键
- g++ - devtoolset-6 正在使用系统 libstdc++ 并且无法链接