专业编程基础技术教程

网站首页 > 基础教程 正文

React 组件生命周期+React AJAX+React 表单与事件+React Refs

ccvgpt 2024-10-11 11:35:54 基础教程 80 ℃

React 组件生命周期

在本章节中我们将讨论 React 组件的生命周期。

React 组件生命周期+React AJAX+React 表单与事件+React Refs

组件的生命周期可分成三个状态:

  • Mounting:已插入真实 DOM

  • Updating:正在被重新渲染

  • Unmounting:已移出真实 DOM

生命周期的方法有:

  • componentWillMount 在渲染前调用,在客户端也在服务端。

  • componentDidMount : 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异部操作阻塞UI)。

  • componentWillReceiveProps 在组件接收到一个新的prop时被调用。这个方法在初始化render时不会被调用。

  • shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。

    可以在你确认不需要更新组件时使用。

  • componentWillUpdate在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。

  • componentDidUpdate 在组件完成更新后立即调用。在初始化时不会被调用。

  • componentWillUnmount在组件从 DOM 中移除的时候立刻被调用。

这些方法的详细说明,可以参考官方文档。

以下实例在 Hello 组件加载以后,通过 componentDidMount 方法设置一个定时器,每隔100毫秒重新设置组件的透明度,并重新渲染:

React 实例

varHello = React.createClass({getInitialState: function(){return{opacity: 1.0}; }, componentDidMount: function(){this.timer = setInterval(function(){varopacity = this.state.opacity; opacity -= .05; if(opacity < 0.1){opacity = 1.0; }this.setState({opacity: opacity}); }.bind(this), 100); }, render: function(){return( <divstyle={{opacity: this.state.opacity}}> Hello{this.props.name} </div> ); }}); ReactDOM.render( <Helloname="world"/>, document.body);

以下实例初始化 statesetNewnumber 用于更新 state。所有生命周期在 Content 组件中。

React 实例

varButton = React.createClass({getInitialState: function(){return{data:0}; }, setNewNumber: function(){this.setState({data: this.state.data + 1})}, render: function(){return( <div> <buttononClick = {this.setNewNumber}>INCREMENT</button> <ContentmyNumber = {this.state.data}></Content> </div> ); }})varContent = React.createClass({componentWillMount:function(){console.log('Component WILL MOUNT!')}, componentDidMount:function(){console.log('Component DID MOUNT!')}, componentWillReceiveProps:function(newProps){console.log('Component WILL RECEIVE PROPS!')}, shouldComponentUpdate:function(newProps, newState){returntrue; }, componentWillUpdate:function(nextProps, nextState){console.log('Component WILL UPDATE!'); }, componentDidUpdate:function(prevProps, prevState){console.log('Component DID UPDATE!')}, componentWillUnmount:function(){console.log('Component WILL UNMOUNT!')}, render: function(){return( <div> <h3>{this.props.myNumber}</h3> </div> ); }});ReactDOM.render( <div> <Button /> </div>, document.getElementById('example'));

React AJAX

React 组件的数据可以通过 componentDidMount 方法中的 Ajax 来获取,当从服务端获取数据库可以将数据存储在 state 中,再用 this.setState 方法重新渲染 UI。

当使用异步加载数据时,在组件卸载前使用 componentWillUnmount 来取消未完成的请求。

以下实例演示了获取 Github 用户最新 gist 共享描述:

React 实例

varUserGist = React.createClass({getInitialState: function(){return{username: '', lastGistUrl: ''}; }, componentDidMount: function(){this.serverRequest = $.get(this.props.source, function(result){varlastGist = result[0]; this.setState({username: lastGist.owner.login, lastGistUrl: lastGist.html_url}); }.bind(this)); }, componentWillUnmount: function(){this.serverRequest.abort(); }, render: function(){return( <div> {this.state.username} 用户最新的 Gist 共享地址: <ahref={this.state.lastGistUrl}>{this.state.lastGistUrl}</a> </div> ); }}); ReactDOM.render( <UserGistsource="https://api.github.com/users/octocat/gists" />, mountNode);

以上代码使用 jQuery 完成 Ajax 请求。

React 表单与事件

本章节我们将讨论如何在 React 中使用表单。

一个简单的实例

在实例中我们设置了输入框 input 值value = {this.state.data}。在输入框值发生变化时我们可以更新 state。我们可以使用 onChange 事件来监听 input 的变化,并修改 state。

React 实例

varHelloMessage = React.createClass({getInitialState: function(){return{value: 'Hello Runoob!'}; }, handleChange: function(event){this.setState({value: event.target.value}); }, render: function(){varvalue = this.state.value; return <div> <inputtype="text"value={value}onChange={this.handleChange} /> <h4>{value}</h4> </div>; }});ReactDOM.render( <HelloMessage />, document.getElementById('example'));

上面的代码将渲染出一个值为 Hello Runoob! 的 input 元素,并通过 onChange 事件响应更新用户输入的值。

实例 2

在以下实例中我们将为大家演示如何在子组件上使用表单。 onChange 方法将触发 state 的更新并将更新的值传递到子组件的输入框的 value 上来重新渲染界面。

你需要在父组件通过创建事件句柄 (handleChange) ,并作为 prop (updateStateProp) 传递到你的子组件上。

React 实例

varContent = React.createClass({render: function(){return <div> <inputtype="text"value={this.props.myDataProp}onChange={this.props.updateStateProp} /> <h4>{this.props.myDataProp}</h4> </div>; }});varHelloMessage = React.createClass({getInitialState: function(){return{value: 'Hello Runoob!'}; }, handleChange: function(event){this.setState({value: event.target.value}); }, render: function(){varvalue = this.state.value; return <div> <ContentmyDataProp = {value}updateStateProp = {this.handleChange}></Content> </div>; }});ReactDOM.render( <HelloMessage />, document.getElementById('example'));


React 事件

以下实例演示通过 onClick 事件来修改数据:

React 实例

varHelloMessage = React.createClass({getInitialState: function(){return{value: 'Hello Runoob!'}; }, handleChange: function(event){this.setState({value: '菜鸟教程'})}, render: function(){varvalue = this.state.value; return <div> <buttononClick={this.handleChange}>点我</button> <h4>{value}</h4> </div>; }});ReactDOM.render( <HelloMessage />, document.getElementById('example'));

当你需要从子组件中更新父组件的 state 时,你需要在父组件通过创建事件句柄 (handleChange) ,并作为 prop (updateStateProp) 传递到你的子组件上。实例如下:

React 实例

varContent = React.createClass({render: function(){return <div> <buttononClick = {this.props.updateStateProp}>点我</button> <h4>{this.props.myDataProp}</h4> </div> }});varHelloMessage = React.createClass({getInitialState: function(){return{value: 'Hello Runoob!'}; }, handleChange: function(event){this.setState({value: 'h5混合开发'})}, render: function(){varvalue = this.state.value; return <div> <ContentmyDataProp = {value}updateStateProp = {this.handleChange}></Content> </div>; }});ReactDOM.render( <HelloMessage />, document.getElementById('example'));

React Refs

React 支持一种非常特殊的属性 Ref ,你可以用来绑定到 render() 输出的任何组件上。

这个特殊的属性允许你引用 render() 返回的相应的支撑实例( backing instance )。这样就可以确保在任何时间总是拿到正确的实例。

使用方法

绑定一个 ref 属性到 render 的返回值上:

<input ref="myInput" />

在其它代码中,通过 this.refs 获取支撑实例:

var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();

完整实例

你可以通过使用 this 来获取当前 React 组件,或使用 ref 来获取组件的引用,实例如下:

React 实例

varMyComponent = React.createClass({handleClick: function(){// 使用原生的 DOM API 获取焦点this.refs.myInput.focus(); }, render: function(){// 当组件插入到 DOM 后,ref 属性添加一个组件的引用于到 this.refsreturn( <div> <inputtype="text"ref="myInput" /> <inputtype="button"value="点我输入框获取焦点"onClick={this.handleClick} /> </div> ); }}); ReactDOM.render( <MyComponent />, document.getElementById('example'));

实例中,我们获取了输入框的支撑实例的引用,子点击按钮后输入框获取焦点。

我们也可以使用 getDOMNode()方法获取DOM元素

最近发表
标签列表