React——学习总结
发布时间:2020-12-15 06:29:58 所属栏目:百科 来源:网络整理
导读:简单开始例子 ReactDOM.render( //React DOM 得render方法 h1Hello,world!/h1,//渲染到html DOM节点得react元素 document.getElementById('root') //获取html页面得DOM节点); JSX JSX, 一种 JavaScript 的语法扩展 React .createElement(component,props,..
简单开始例子ReactDOM.render( //React DOM 得render方法 <h1>Hello,world!</h1>,//渲染到html DOM节点得react元素 document.getElementById('root') //获取html页面得DOM节点 ); JSX
JSX, 一种 JavaScript 的语法扩展
1、JSX中使用JavaScript 表达式用大括号{}包起来; const element = (//换行用小括号括起来 <div> <h1 className={aclass}>Hello!</h1> {/*属性用小驼峰命名方式,变量aclass用{}括起来*/} <h2>{2+2}</h2> {/*js表达式用{}括起来*/} </div> ); //可以用点表示法来引用 React 组件 import React from 'react'; const MyComponents = {//一个模块包含多个组件。 DatePicker: function DatePicker(props) { return <div>Imagine a {props.color} datepicker here.</div>; } } function BlueDatePicker(props) { return <MyComponents.DatePicker color="blue" checked />;//点表示法 checked 值为true //return <MyComponents[props.componentTtye] color="blue" />;错误:JSX 标签名不能为一个表达式 //const componentType = MyComponents[props.componentTtye] ;return <componentType color="blue" /> //正确。 } 元素渲染1、元素是构成 React 应用的最小单位; 组件 & Props1、组件得含义与定义
组件可以将UI切分成一些的独立的、可复用的部件,从概念上看就像是
函数,它可以接收任意的参数(称之为“props”),所有的React组件必须像
//函数定义组件 function Welcome(props) {//参数props return <h1>Hello,{props.name}</h1>;//返回react 元素 } //ES6 class定义组件 class Welcome extends React.Component { //扩展ES6类React.Component render() {//render()函数体 return <h1>Hello,{this.props.name}</h1>; } } 当React遇到的元素是用户自定义的组件,它会将 JSX属性作为单个对象(props)传递给该组件,这个对象称之为“ function Welcome(props) { //自定义组件 return <h1>Hello,{props.name}</h1>;//props={name:"Sara"} } const element = <Welcome name="Sara" />; ReactDOM.render( element,//元素为自定义组件Welcome document.getElementById('root') ); 2、组合组件 组件可以在它的输出中引用其它组件,React应用中,按钮、表单、对话框、整个屏幕的内容等,这些通常都被表示为组件。组件的返回值只能有一个根元素。 function App() { return ( <div>{/*一个根元素*/} <Welcome name="Sara" />{/*引用自定义Welcome组件*/} <Welcome name="Cahal" /> <Welcome name="Edite" /> </div> ); } State & 生命周期1、state 1、局部状态State:一个功能只适用于类定义组件; 2、生命周期 挂载:组件加载到DOM中, class Clock extends React.Component { constructor(props) { //基础构造函数 super(props); //传递props this.state = {date: new Date()}; //唯一初始化this.state得地方 } componentDidMount() {//react 元素添加到DOM中后 this.timerID = setInterval( () => this.tick(),1000 ); } componentWillUnmount() {//react 元素即将从DOM中删除 clearInterval(this.timerID); } tick() { this.setState({ //更改state得值 date: new Date() }); /*回调函数得方式更改state得值 this.setState((prevState,props) => ({ date: prevState.date + 1 }));*/ } render() { return ( <div> <h1>Hello,world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2>{/*每次state更新时调用render方法重新渲染值*/} </div> ); } } ReactDOM.render(//初次调用render渲染clock组件到DOM中 <Clock />,document.getElementById('root') ); 事件处理1、React事件绑定属性的命名采用 class LoggingButton extends React.Component { // This syntax ensures `this` is bound within handleClick. // Warning: this is *experimental* syntax. handleClick = () => {//属性初始化器法绑定this console.log('this is:',this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } } class LoggingButton extends React.Component { /*构造函数中绑定this constructor(props) { super(props); // This binding is necessary to make `this` work in the callback this.handleClick = this.handleClick.bind(this); }*/ handleClick() { console.log('this is:',this); } render() { // This syntax ensures `this` is bound within handleClick return ( <button onClick={(e) => this.handleClick(e,id)}>{/*箭头函数方法,用构造函数中绑定this时可直接调用this.handleClick*/} Click me </button> ); } } 条件渲染1、使用 JavaScript 操作符 if 或条件运算符来创建表示当前状态的元素 满足条件return元素; function WarningBanner(props) { if (!props.warn) { return null; //返回null不渲染元素 } const a = <a>超链接</a>;//存储元素到变量 if (props.warn == “a”) {//if条件句 return元素,tia'jian渲染 return a; } return ( <div className="warning"> Warning! </div> ); } class Page extends React.Component { constructor(props) { super(props); this.state = {showWarning: true} this.handleToggleClick = this.handleToggleClick.bind(this); } handleToggleClick() { this.setState(prevState => ({ showWarning: !prevState.showWarning })); } render() { return ( <div> <WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}> {this.state.showWarning ? 'Hide' : 'Show'}{/*三目运算符选择渲染文本*/} </button> {this.props.warn=="b" && <a>b超链接</a>} // &&条件渲染 </div> ); } } ReactDOM.render( <Page />,document.getElementById('root') ); 列表 & Keys1、map() function ListItem(props) { // 对啦!这里不需要指定key: return <li>{props.value}</li>; } function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // 又对啦!key应该在数组的上下文中被指定 <ListItem key={number.toString()} value={number} /> ); return ( <ul> {listItems} {numbers.map((number)=> <ListItem value={number} key={index}/> ) } </ul> ); } const numbers = [1,2,3,4,5]; ReactDOM.render( <NumberList numbers={numbers} />,document.getElementById('root') ); 表单1、受控组件(<input>,<textarea>,<select>): class Reservation extends React.Component { constructor(props) { super(props); this.state = { isGoing: true,numberOfGuests: 2 }; this.handleInputChange = this.handleInputChange.bind(this); } handleInputChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; //判断type const name = target.name; //根据target.name来设定值。 this.setState({ [name]: value }); } render() { return ( <form> <label> Is going: <input name="isGoing" type="checkbox" checked={this.state.isGoing} onChange={this.handleInputChange} /> </label> <br /> <label> Number of guests: <input name="numberOfGuests" type="number" value={this.state.numberOfGuests} onChange={this.handleInputChange} /> </label> </form> ); } } 状态提升1、 通过将state数据提升至离需要这些数据的组件最近的父组件来完成的。这就是所谓的状态提升; 组合 vs 继承1、React 具有强大的组合模型,我们建议使用组合而不是继承来复用组件之间的代码; function Dialog(props) { return ( <FancyBorder color="blue"> <h1 className="Dialog-title"> {props.title} </h1> <p className="Dialog-message"> {props.message} </p> {props.children} </FancyBorder> ); } class SignUpDialog extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSignUp = this.handleSignUp.bind(this); this.state = {login: ''}; } render() { return ( <Dialog title="Mars Exploration Program" message="How should we refer to you?"> <input value={this.state.login} onChange={this.handleChange} /> <button onClick={this.handleSignUp}> Sign Me Up! </button> </Dialog> ); } handleChange(e) { this.setState({login: e.target.value}); } handleSignUp() { alert(`Welcome aboard,${this.state.login}!`); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |