React组件传值
react内组件传值主要有三种: 父组件向子组件传值 、 子组件向父组件传值 、 以及 兄弟组件之间的传值
一、父组件 - - - > 子组件
父组件向子组件传值是通过 props 来传,在子组件中用 this.props.xx 接收父组件传来的值
class Father extends React.Component {
constructor(props) {
super(props)
this.state = {
fatherName: "Father"
}
}
render() {
return (
<div>
<Child fatherName={this.state.fatherName} />
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
My Father's name is "{this.props.fatherName}"
</div>
)
}
}
ReactDOM.render(<Father />, document.querySelector(".app"))
二、 子组件 - - - > 父组件
父组件通过props向子组件传入一个方法,子组件在通过调用该父组件的方法,将数据以参数的形式传给父组件,父组件可以在该方法中对传入的数据进行处理;(简单点说就是:子组件通过调用父类方法来实现对父组件的传值)
class Father extends React.Component {
constructor(props) {
super(props)
this.state = {
message:""
}
}
getMsg = (msg)=>{
this.setState({
message: msg
})
}
render() {
return (
<div>
Message : {this.state.message}
<br/>
<Child getMsg={this.getMsg} />
</div>
)
}
}
class Child extends React.Component {
sendMsg = ()=>{ // 用一个函数来调用 父组件 传入的函数
this.props.getMsg("Hello Father")
}
render() {
return (
<button onClick={this.sendMsg}>send the msg</button>
)
}
}
ReactDOM.render(<Father />, document.querySelector(".app"))
点击前 ----> 点击后
三、 兄弟组件之间的传值
兄弟组件之间的传值原理:
状态提升
即多个组件都在重复使用同一个状态值,可以将这个值 提升 至父组件中保存,相当于数据复用;当然如果想实现一个子组件向另一个子组件传值,也可以通过父组件这层“媒介”。(即 数据状态 被多个子组件共享使用,应该抽离到父组件,并且修改数据的相关逻辑都应该写在父组件,来方便子组件调用)
eg. 让外我们来通过下面这个案例加深理解:父组件 Father 包含着两个子组件 ChildContext 和 ChildButton ,一开始 默认 登录状态为 false ,当我们点击 login 按钮 时, 子组件ChildButton 会把 状态 传给 父组件,父组件再把该 状态 传给 ChildContext ,收到 状态 改变后,ChildContext 内改变其显示的内容
class Father extends React.Component {
constructor(props) {
super(props)
// 状态设置在哪个组件,修改行为就在哪个组件
// 如果数据状态被多个子组件共享使用,应该抽离到父组件
this.state = {
isLogin: false
}
}
login = () => {
this.setState({ isLogin: true })
}
logout = () => {
this.setState({ isLogin: false })
}
render() {
return (
<div>
<ChildContext isLogin={this.state.isLogin} />
<ChildButton isLogin={this.state.isLogin} login={this.login} logout={this.logout} />
</div>
)
}
}
function ChildContext(props) {
let {isLogin} = props
return (
<div>
<h1>{isLogin ? "Welcome to here" : "Please Login First"}</h1>
</div>
)
}
function ChildButton(props) {
// 解构拿到父组件传的 值 或 函数
let {isLogin,login,logout} = props
return (
<div>
<button onClick={isLogin ? logout : login}>{isLogin ? "Logout" : "Login"}</button>
</div>
)
}
ReactDOM.render(<Father />, document.querySelector(".app"))
<–点击后的变换–>