我正在学习React Js
,但我会知道与这个库通信多个组件。例如:
文件1.jsx
class fileOne extends Component{
//get some value
//do something
//send value to file2
}
文件2.jsx
class fileTwo extends Component{
//recive some value
//do something
//and return some value
//to file1
}
file3.jsx
class fileThree extends Component{
//recive some value
//do something
//and return some value
//to file1
}
此文件是否位于同一文件夹中并不重要。
最佳答案
文件一包含我们的状态,我们可以通过将此状态作为 prop 传递给任何组件。
我将包含“hello”的 this.state.greeting 作为名为greeting 的 prop 传递给 fileTwo 组件。
您还希望类名称以大写字母开头。
class FileOne extends Component{
state={greeting:'hello'}
render() {
return (
<div>
<FileTwo greeting={this.state.greeting}/>
<FileThree greeting={this.state.greeting} />
</div>
)
}
}
FileTwo 可以使用 this.props
访问来自 fileOne 的问候语。我们可以使用大括号来渲染它。
class FileTwo extends Component{
render() {
return (
<div>This is the greeting {this.props.greeting} </div>
)
}
}
函数式无状态组件可以从父组件 FileOne 接收 props。
const FileThree = (props) => <div>
This is the third file component,
it can recieve props just like the second file {props.greeting}
</div>
关于javascript - 如何通信多个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49373223/