组件的实例对象三大属性
这三个核心都是建立在类定义的组件上,因为函数建立的组件没有,因此称为组件的实例对象三大属性
1. state的简写方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello,React study by nanchengyu</title> </head> <body> <div id="test"></div> <!--引入React核心库 引入顺序有要求必须按照下方1在2前--> <script type="text/javascript" src="../js/react.development.js"></script> <script type="text/javascript" src="../js/react-dom.development.js"></script> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel"> /*此处一定要写babel*/ //1.创建类组件 class Weather extends React.Component { //1.1 初始化状态 state ={isHot:false,wind:'微风'} render() { //读取状态 const {isHot,wind} = this.state return <h2 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h2> } //1.2 自定义方法 用赋值语句的形式+箭头函数 changeWeather =()=>{ const isHot = this.state.isHot this.setState({isHot:!isHot}) } } //2.渲染组件到test上 ReactDOM.render(<Weather/>, document.getElementById('test')) </script> </body> </html>
2. props的简写
props 用于从父组件传递数据给子组件,而 state 用于管理组件内部的状态。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello,React study by nanchengyu</title> </head> <body> <div id="test"></div> <div id="test1"></div> <div id="test2"></div> <!--引入React核心库 引入顺序有要求必须按照下方1在2前--> <script type="text/javascript" src="../js/react.development.js"></script> <script type="text/javascript" src="../js/react-dom.development.js"></script> <script type="text/javascript" src="../js/babel.min.js"></script> <!--用于对组件标签属性的限制--> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel"> /*此处一定要写babel*/ //1.创建类组件 class Person extends React.Component { static propTypes = { name:PropTypes.string.isRequired, /*对Person类的属性进行限制*/ sex:PropTypes.string, age:PropTypes.number, speak:PropTypes.func, } static defaultProps = { sex: '男', age: 18 } //状态写在属性后面 // state ={isHot:false,wind:'微风'} render() { //读取状态 const {name, age, sex} = this.props //props是只读状态 return ( <ul> <li>姓名:{name}</li> <li>年龄:{age}</li> <li>性别:{sex}</li> </ul> ) } } //2.渲染组件到test上 ReactDOM.render(<Person name="ncy" age={20} sex="男" speak="1"/>, document.getElementById('test')) ReactDOM.render(<Person name="nanchengyu" age={20} sex="男"/>, document.getElementById('test1')) ReactDOM.render(<Person name="wife" age={20} sex="女"/>, document.getElementById('test2')) // function speak(){ // console.log("全网同名:南城余") // } </script> </body> </html>
3. refs
refs类似于原生的id标签 用于表示html标签<>