// 父组件传值到子组件中。
class WebSite extends React.Component { constructor() { super(); this.state = { name: "菜鸟教程", site: "https://www.runoob.com" } } render() { return ( <div> <Name name={this.state.name} /> <Link site={this.state.site} /> </div> ); } } class Name extends React.Component { render() { return ( <h1>{this.props.name}</h1> ); } } class Link extends React.Component { render() { return ( <a href={this.props.site}> {this.props.site} </a> ); } } ReactDOM.render( <WebSite />, document.getElementById('example') );
//react 生命周期
class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { //这在 React 中被称为挂载 (请求数据在此方法中) this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { //这在 React 中被称为卸载 clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <div> <h1>Hello, world!</h1> <h2>现在是 {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } ReactDOM.render( <Clock />, document.getElementById('example') );