在进行react开发中,最常用的就是props和state。我们今天做一个按钮点击的例子,来说明下props和state分别用说明作用
1.在项目出口文件中,我们直接渲染Button01组件。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';import Button01 from './button01.jsx';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<Button01 />, document.getElementById('root'));
registerServiceWorker();2.button01.jsx代码
import React from 'react';
import Button02 from './button02'
class Button01 extends React.Component {
constructor(props) {
super(props);
this.state = {
display: false
}
}
render() {
return (
<div onClick={() => {
this.setState({
display: false
})
}}>
<Button02 display={this.state.display}/>
<Button02 display={this.state.display}/>
<Button02 display={this.state.display}/>
<Button02 display={this.state.display}/>
<Button02 display={this.state.display}/>
</div>
)
}
}
export default Button01;3.button02.jsx代码
import React from 'react';
class button extends React.Component {
constructor(props) {
super(props);
this.state = {
display: this.props.display
}
}
componentWillMount() {
console.log('componentWillMount-', this.state.display)
}
componentWillReceiveProps(nextProps) {
console.log("->", nextProps.display);
if (this.state.display) {
this.setState({
display: nextProps.display
})
}
}
render() {
return (
<div>
<button onClick={() => {
this.setState({
display: !this.state.display
})
}}>
点击
<div style={{
backgroundColor: 'green',
width: 50,
height: 50,
display: this.state.display ? 'block' : 'none'
}}>
</div>
</button>
</div>
)
}
}
export default button;
本文通过一个按钮点击示例,介绍了React应用中State与Props的基本使用方式。演示了如何在父组件中设置State,并通过Props传递给子组件,同时展示了按钮点击事件触发State更新的过程。
1524

被折叠的 条评论
为什么被折叠?



