同一个组件中用 state 传递
import React, { Component } from 'react' import { render } from 'react-dom' class Home extends Component { constructor(props) { super(props) //更改所有状态 更改单个状态需具体选中 列如:this.state.str = 'Bye' this.state = { str: 'Hello' } } render() { return( <div> <!-- 同一个组件中用state传递 --> <h1>{this.state.str}</h1> </div> ) } }
父组件向子组件传递用 props
import React, { Component } from 'react' import { render } from 'react-dom' //父组件 class App extends Component { constructor (props) { super(props) this.state = { str: 'Hello', boolean: true } this.clickHandle = this.clickHandle.bind(this) } clickHandle() { //注意只有setState才会引起子组件的重新渲染,this.state 只能改变组件自身重新渲染 this.state.str = 'Bye' this.setState({boolean: !this.state.boolean }) } render() { var name = this.state.boolean ? 'sjy' : 'abc' return( <div> //注入状态中的str 传递状态中的name 传递clickHandle这个方法 给子组件Name <span>{this.state.str}</span><Name name={name} clickHandle={this.clickHandle} /> <App/> </div> ) } } //子组件 react创建组件的防方法有两种 1.React.Component 2.createClass 有一定的区别! let Name = React.createClass({ getInitialState: function(){ return( {status: 'ok'} ) }, render: function(){ return ( //react中点击事件的绑定 注意是驼峰模式的另外类名必须是用className <span className="anyone" onClick={this.props.clickHandle}> {this.props.name}</span> ) } }) //别忘了渲染 render(( <App/> ),document.getElementById('app-wrapper'))
运行效果:
结束
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于