父子组件更改数据
父组件修改子组件state(不建议):
父组件获取到子组件的实例(通过refs--(已被弃用)),通过子组件的setSate()来更改子组件state
父组件
<Child ref="child"></Child>
this.refs.child.setState({msg:'hello'})
子组件改父组件state:
父组件传递修改自己的setState函数给子组件调用
父组件文件
//父组件
import React, { Component } from 'react'
import Child from './2-Child'
class PC extends Component {
constructor(props) {
super(props);
this.state = {
parentMSg: 'parentMSg'
}
}
//传递的修改自己state的函数
changeParentState = () => {
this.setState({ parentMSg: 'hello' })
}
render() {
return (
<div>
<Child parentMSg={this.state.parentMSg} changeParentState={this.changeParentState}></Child>
</div>
)
}
}
export default PC
子组件文件
//子组件
import React, { Component } from 'react'
class Child extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>父组件数据:{this.props.parentMSg}</p>
//调用父组件的setState函数
<button onClick={this.props.changeParentState}>更改父组件数据</button>
</div>
)
}
}
export default Child
在jsx中添加样式
行内样式
使用双花括号,第一个花括号代表变量,第二个花括号代表对象
<div style={
{cplor:'red'}}></div>
const btnStyle={
width:100,