react 基础篇学习
JSX
- 标签即js变量
- 使用 {msg} 包裹变量
- 标签属性也可以使用变量 <img name={tutu} / >
元素渲染
const element = <h1>haha</h1> reactDom.render( element, document.getElementById('root') )
只有调用reactDom.render才会重新渲染
组件
- 函数组件
function hello(props){ return <h2>你好, props.name<h2> }
- class组件(使用props的时候需要加this)
class Hello extends React.Compenent { return <h2>你好, this.props.name<h2> }
- props是只读的
如何使用state
class Clock extends ReactCompenent { constructor(props){ super(props) this.date = {date: new Date()} } componentDidMount(){ this.timerId = setInterval( ()=>this.tick() ) } compenentwillunmount(){ clearInterval(this.timeID) } tick(){ this.setSate({ date: new Date() }) } render(){ return <h2>it is {this.state.date.toLocaleTimeString()}<h2> } }
- 在更改state的数据时,不能直接更改(this.state.date = '...),需要使用this.setState({date: '....'})
- this.setState({ date: '...' })是可以合并对象的,只单独对某个属性做更改就可以合并到原对象上去
- 异步更新
// Wrong this.setState({ counter: this.state.counter + this.props.increment, }); // Correct this.setState((state, props) => ({ counter: state.counter + props.increment }));
事件处理
- 如果是函数组件,直接使用JSX语法调用即可
<button onclick={handleClick}> function handleclick() { alert('hi') }
- 如果是class组件,一定要注意this问题,绑定this的方式有如下三种
constructor(props) { super(props); this.state = {isToggleOn: true}; // 为了在回调中使用 `this`,这个绑定是必不可少的 this.handleClick = this.handleClick.bind(this); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); }
class LoggingButton extends React.Component { // 此语法确保 `handleClick` 内的 `this` 已被绑定。 // 注意: 这是 *实验性* 语法。 handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // 此语法确保 `handleClick` 内的 `this` 已被绑定。 return ( <button onClick={() => this.handleClick()}> Click me </button> ); } }
条件渲染
- 可以通过条件运算符&&写到JSX表达式中从而控制是否渲染
- 三目运算符同理
- 通过if else 写两个状态组件也可以
列表&key
class hello extends React.Compenent { constructor(props){ super(props) this.state = { msg: '你好', number:[1,2,3,4,5] } } render(){ const lists = this.state.numbers.map((num)=>{ <li key={num.toString()}>this is number:{num}</li> }) return( <ul> {lists} </ul> ) } }
表单
组合继承(相当于vue中slot)
- 使用children这个特殊的prop
function hello(props){ return ( <div> <h2>{props.msg}</h2> {props.children} </div> ) } function welcome(props){ return { <hello msg='hello,tutu'> <p>welcome~~<p> </hello> } } ReactDom.render( <welcome />, document.getElementById('root') )