标签:状态 exp render pre like extends efault onclick back
props属性:
我使用代码来说明React中props属性:
// Profile.jsx import React from ‘react‘ ; export default Class Profile extends React.Component { // render 是这个组件渲染的Vitrual DOM结构 render() { return ( <div className-"profile-component"> </*this.props就是传入的属性*/> <h1>my name is {this.props.name}</h1> <h2>my age is {this.props.age}</h2> </div> ) } }
用这种方式,就实现了一个React的组件,在其他的组件中,可以像HTML标签一样引用它。有了组件以后,可以使用React提供的另外一个库ReactDOM把这个组件挂载到DOM节点上。
// app.jsx import { render } from ‘react-dom‘; import Profile from ‘./profile‘; render(<Profile name="lewis" age=26 />, document.getElementById(‘app‘)); // 或者可以使用...属性拓展 const props = { name: ‘lewis‘, age: 26 }; render(<Profile {...props} />, document.getElementById(‘app‘));
state状态:
//Profile.jsx export default class Profile extends React.Component { constructor (props) { super (props); this.state = { liked: 0 }; this.likedCallback = this.likedCallback.bind(this); } likedCallback() { let liked = this.state.liked; liked++; this.setState({ liked }); } render() { return ( <div> <h1>我的名字叫{this.props.name}</h1> <h2>我今年{this.props.age}</h2> <button onClick={this.likedCallback}>点赞</button> <h2>总点赞数:{this.state.liked}</h2> </div> ) } }
this.likedCallback = this.likedCallback.bind(this);
标签:状态 exp render pre like extends efault onclick back
原文地址:https://www.cnblogs.com/xiaojuziya/p/11094477.html