本文共 3810 字,大约阅读时间需要 12 分钟。
import React from 'react'; // 此句不能少import ReactDom from 'react-dom';class Taggle extends React.Component{ state = { flag: true } handleClick(e){ e.preventDefault() // 阻止默认行为,要放在开头 console.log(e); console.log(e.target); // target为html标签 // this.state.flag = !this.state.flag; // 修改state状态 this.setState({flag: !this.state.flag}) // 官方推荐这样修改state } render(){ return{/*必须bind,不然this没有定义*/} {this.state.flag.toString()} {/*注意必须转换成字符串*/}}}class Sub extends React.Component{ // 子组件 render(){ // return sub element ==== {'2>1?true:false'} // true和false打印不出来,必须改为字符串 return sub element ==== {true.toString()} }} // class component,类名必须是大驼峰,所有标签必须封口,单标签也得封口,所有标签都是小写class App extends React.Component{ // First就是组件,就是元素,组件名第一个字母必须大写开头 state = { // state是一个对象,state的变化会影响render函数的执行 p1: 'Curry', p2: '.Klay' } // render组件的渲染函数 render(){ console.log('~~~~~~~~~~~~~') //this.state.p1 = 'Warriors' // 修改了p1的内容,但是不建议这样修改 // this.setState({p1: 'Warriors'}) // 放在这里会递归 setTimeout(() => this.setState({p1: 'Warriors'}), 3000) // 注意这里还是有递归的,只是后来虚拟DOM没有改变,浏览器没有重新渲染 // returnApp Component; // 只能有一个顶级元素 return{this.state.p1}{this.state.p2}}}class Second extends React.Component{ // First就是组件,就是元素 // render组件的渲染函数 render(){ return React.createElement('div', null, 'test string'); }}
import React from 'react'import ReactDom from 'react-dom'class Toggle extends React.Component{ constructor(props){ super(props) this.state = { flag: true, count: 0 } } // state = { // flag: true, // count: 0 // } handleClick(e){ // console.log(e) // console.log(e.target) // target为id=t1的div标签 // console.log(this) // // this.setState({flag: !this.state.flag}) this.setState({count: this.state.count + 1}) } // handleOver(e){ // this.setState({count: this.state.count + 1}) // } render(){ console.log('render taggle') return{/* 一定要用bind绑定this,否则直接结果是undefined,参考之前篇幅的this的坑 */} {/* style标签里第一大括号是表达式,第二个大括号是对象 */} {this.state.flag.toString()}---{this.state.count} {this.props.name}{this.props.parent.state.myname} {this.props.children} {/* 可以拿到Toggle的所有子标签的内容 */}}}// props属性在内部是只读属性,不能修改,要想修改,需要从外部注入class App extends React.Component{ constructor(props){ super(props) // 必须调用super父类构造器,否则报错 this. state = { // 类中定义state // p1: 'Curry', // p2: '.Klay', childName: 'Curry', myname: '.warriors', count: 0 } } // state = { // // p1: 'Curry', // // p2: '.Klay', // childName: 'Curry', // myname: '.warriors', // count: 0 // } handleClick(e){ // this.setState({childName: this.state.childName + '1'}) this.setState({count: this.state.count + 1}) } render(){ console.log('APP render') setTimeout(() => this.setState({p1: 'Warriors'}), 3000); // 每隔3秒 return{/* {this.state.p1}{this.state.p2} */} {/* child's name = {this.state.childName} */} count = {this.state.count}}}ReactDom.render(
{/* 自定义了两个属性通过props传给Toggle组件对象 */} 金州拉文 勇士总冠军(我是锚点) {/*a和span标签是Toggle的子元素 ,子元素通过props.children访问*/} , document.getElementById('root'))
转载地址:http://avfvi.baihongyu.com/