React JS 基础知识17条

时间:2023-03-09 18:19:41
React JS 基础知识17条

1. 基础实例

    <!DOCTYPE html>
<html>
<head>
<script src="../build/react.js"></script>
<script src="../build/react-dom.js"></script>
<script src="../build/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
</script>
</body>
</html>

说明:

(1).react.js:React 的核心库。
(2).react-dom.js:提供与 DOM 相关的功能。
(3).Browser.js:将 JSX 语法转为 JavaScript 语法。这一步很消耗时间,实际上线的时候,应该将它放到服务器完成,操作如下:
    $ babel src --out-dir build
  将 src 子目录的 js 文件进行语法转换,转码后的文件全部放在 build 子目录。
(4).text/babel:凡是使用 JSX 的地方,都要加上 type="text/babel"。

2. ReactDOM.render()

用于将模板转为 HTML 语言,并插入指定的 DOM 节点。

ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);

  

3. JSX 允许直接在模板插入 JavaScript 变量。如果这个变量是一个数组,则会展开这个数组的所有成员

    var arr = [
<h1>Hello world!</h1>,
<h2>React is awesome</h2>,
];
ReactDOM.render(
<div>{arr}</div>,
document.getElementById('example')
);

  

4. React.createClass()
  生成一个组件类。

5. class 属性需要写成 className ,for 属性需要写成 htmlFor ,这是因为 class 和 for 是 JavaScript 的保留字。

6. React.Children.map()
  用来遍历子节点,而不用担心 this.props.children 的数据类型是 undefined 、object 、array。
  this.props.children 的值有三种可能:
  数据类型undefined:当前组件没有子节点;
  数据类型object:有一个子节点;
  数据类型array: 有多个子节点。

var NotesList = React.createClass({
render: function() {
return (
<ol>
{
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
}
</ol>
);
}
});
ReactDOM.render(
<NotesList>
<span>hello</span>
<span>world</span>
</NotesList>,
document.body
);

姊妹属性还有
React.Children.map :遍历,返回对象
React.Children.forEach :遍历,不返回对象
React.Children.count :返回 children 当中的组件总数
React.Children.only :返回 children 中仅有的子级。否则抛出异常

7. 组件类的 PropTypes 属性,就是用来验证组件实例的属性是否符合要求

    var MyTitle = React.createClass({
propTypes: {
title: React.PropTypes.string.isRequired,//只接受string类型的,且必须传
}, render: function() {
return <h1> {this.props.title} </h1>;
}
});

姊妹属性:

React.PropTypes.array
React.PropTypes.bool
React.PropTypes.func
React.PropTypes.number
React.PropTypes.object
React.PropTypes.string
React.PropTypes.node // 所有可以被渲染的对象:数字,字符串,DOM 元素或包含这些类型的数组。
React.PropTypes.element // React 元素
React.PropTypes.instanceOf(Message) // 用 JS 的 instanceof 操作符声明 prop 为类的实例
React.PropTypes.oneOf(['News', 'Photos']) // 用 enum枚举 来限制 prop 只接受指定的值。
React.PropTypes.oneOfType([React.PropTypes.string,React.PropTypes.number,React.PropTypes.instanceOf(Message)]) // 指定的多个对象类型中的一个
React.PropTypes.arrayOf(React.PropTypes.number) // 指定类型组成的数组(如只接受数字组成的数组)
React.PropTypes.objectOf(React.PropTypes.number) // 指定类型的属性构成的对象(如只接受数字组成的对象)
React.PropTypes.shape({color: React.PropTypes.string,fontSize: React.PropTypes.number}) // 特定形状参数的对象(字符串颜色,数字字体) 以后任意类型加上 'isRequired' 来使 prop 不可空。
React.PropTypes.func.isRequired
React.PropTypes.any.isRequired //不可空的任意类型

8. getDefaultProps()设置组件属性默认值

    var MyTitle = React.createClass({
getDefaultProps : function () {
return {
title : 'Hello World'//没传递就用默认值
};
}, render: function() {
return <h1> {this.props.title} </h1>;
}
}); ReactDOM.render(
<MyTitle />,
document.body
);

9. ref 获取真实DOM

React组件生成的是虚拟DOM,只有插入到页面中后才能变成真实的DOM。
任何DOM变动,都先在虚拟DOM上发生,然后再将实际发生变动的部分,反映在真实 DOM上,这种算法叫做 DOM diff ,它可以极大提高网页的性能表现。
但是,有时需要从组件获取真实 DOM 的节点,这时就要用到 ref 属性。

    var MyComponent = React.createClass({
handleClick: function() {
this.refs.myTextInput.focus();// this.refs.myTextInput 获取真实的Input DOM
},
render: function() {
return (
<div>
<input type="text" ref="myTextInput" />
<input type="button" value="Focus the text input" onClick={this.handleClick} />
</div>
);
}
}); ReactDOM.render(
<MyComponent />,
document.getElementById('example')
);

说明:
(1) 由于真实DOM发生在虚拟DOM之后,所以this.refs.[refName]必须等到虚拟 DOM 插入文档以后,才能使用这个属性,否则会报错。
(2) ref是获取当前节点的真实DOM;this.getDOMNode()是获取真个组件的真实DOM;两者都必须要在组件加载完成后使用。

10. React 事件

剪贴板事件:
onCopy
onCut
onPaste
键盘事件:
onKeyDown
onKeyPress
onKeyUp
鼠标事件:
onClick
onDoubleClick
onDrag
onDragEnd
onDragEnter
onDragExit
onDragLeave
onDragOver
onDragStart
onDrop
onMouseDown
onMouseEnter
onMouseLeave
onMouseMove
onMouseOut
onMouseOver
onMouseUp
onWheel :鼠标滚轮滚动事件
触摸事件:
onTouchCancel
onTouchEnd
onTouchMove
onTouchStart
焦点事件:
onFocus
onBlur
表单事件:
onChange
onInput
onSubmit
UI 事件:
onScroll
事件说明参考:http://reactjs.cn/react/docs/events.html

11. this.state 和 this.props
  每个React组件都是一个状态机,一旦状态改变(与用户发生交互)就会重新渲染组件,这就是 this.state。
  每个组件又有初始化所需要的数据,一旦初始化完成,该数据就不再变动,这就是 this.props。

    var LikeButton = React.createClass({
getInitialState: function() {
return {liked: false};
},
handleClick: function(event) {
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
</p>
);
}
}); ReactDOM.render(
<LikeButton />,
document.getElementById('example')
);

12. 表单
  表单包括:input、textarea、checkbox、radio、option.
  监听表单组件变化使用 onChange 事件,通过以下属性获取对应值:
    value:表单input、textarea;
    checked:表单checkbox、radio;
    selected:表单option。

    var Input = React.createClass({
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function () {
var value = this.state.value;
return (
<div>
<input type="text" value={value} onChange={this.handleChange} />
<p>{value}</p>
</div>
);
}
});
ReactDOM.render(<Input/>, document.body);

  

13. 组件生命周期

生命周期三个状态:
(1)Mouting:已插入真实 DOM
(2)Updating:正在被重新渲染
(3)Unmounting:已移出真实 DOM
三个状态对应 5 个函数 + 2 个特殊处理:
(1)componentWillMount:初始化渲染之前调用(只在第一次渲染时调用,后续重新渲染、修改props/state 都不在调用)。
              允许调用setState(),组件直接使用新的state,而不会引起第二次渲染。
(2)componentDidMount:初始化渲染之后调用(只在第一次渲染时调用,后续重新渲染、修改props/state 都不在调用)。
              jQuery操作DOM(如ref、getDOMNode使用)、调用外部JS方法(通过props传递)等都可以在这里操作。
(3)componentWillUpdate:修改props/state 重新渲染之前调用(第一次渲染时不调用)。
                不允许调用setState(),会造成死循环。
(4)componentDidUpdate:修改props/state 重新渲染之后调用(第一次渲染时不调用)。
               不允许调用setState(),会造成死循环。
               jQuery操作DOM(如ref、getDOMNode使用)、调用外部JS方法(通过props传递)等都可以在这里操作。
(5)componentWillUnmount:组件被移除时调用(比如在div中渲染组件1,然后再渲染组件2,此时组件1被移除)。
                 执行任何必要的清理,比如无效的定时器,或者清除在 componentDidMount 中创建的 DOM 元素。

(6)componentWillReceiveProps(object nextProps):修改props 重新渲染 之前调用(第一次渲染时不调用;如果props和之前一样,也会执行)。
                           允许调用setState(),组件直接使用新的state,而不会引起第二次渲染。
                           该方法中this.props可以获取老props,参数nextProps才表示新的props。
(7)shouldComponentUpdate:是否需要重新渲染组件。修改props/state 重新渲染之前调用(第一次渲染时不调用)。
                true 表示需要重新渲染;false 表示不需要重新渲染,即不会调用后续的componentWillUpdate 和 componentDidUpdate。
                优化性能的关键函数:该方法可以实现新老props 和 state 的比对逻辑,自定义是否重新渲染。组件较多时,可提升性能。
总结:
  各个生命周期函数的先后顺序:
  初始化渲染阶段:componentWillMount > componentDidMount
  修改state 阶段:shouldComponentUpdate > componentWillUpdate > componentDidUpdate
  修改props 阶段:componentWillReceiveProps > shouldComponentUpdate > componentWillUpdate > componentDidUpdate
  旧组件卸载阶段:旧组件 componentWillUnmount > 新组件生命周期
生命周期测试实例:

   <!DOCTYPE html>
<html>
<head>
<script src="../build/react.js"></script>
<script src="../build/react-dom.js"></script>
<script src="../build/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
var Hello = React.createClass({
getInitialState: function () {
console.log('组件1getInitialState被执行');
return {
name: this.props.name
};
},
componentWillMount: function() {
console.log('组件1:componentWillMount');
},
componentDidMount: function() {
console.log('组件1:componentDidMount');
},
componentWillUpdate: function() {
console.log('组件1:componentWillUpdate');
// this.setState({name: '内部componentWillUpdate更新state'});//会造成死循环,一直加载组件
},
componentDidUpdate: function() {
console.log('组件1:componentDidUpdate');
},
componentWillUnmount: function() {
console.log('组件1:被卸载:componentWillUnmount');
},
componentWillReceiveProps: function(nextProps) {
console.log('组件1:componentWillReceiveProps:老props:'+this.props.name+';新props:'+nextProps.name);
},
shouldComponentUpdate: function() {
console.log('组件1:shouldComponentUpdate');
return true;// true 表示需要重新渲染;false 表示不需要重新渲染,即不会调用后续的componentWillUpdate和componentDidUpdate。
},
handleClick: function(event) {
console.log('修改state重新渲染组件1:');
this.setState({name: '内部更新state'});
}, render: function () {
return (
<div onClick={this.handleClick}>
Hello {this.state.name}
</div>
);
}
}); var Hello2 = React.createClass({
getInitialState: function () {
console.log('组件2:getInitialState被执行');
return {
name: this.props.name
};
},
componentWillMount: function() {
console.log('组件2:componentWillMount');
},
componentDidMount: function() {
console.log('组件2:componentDidMount');
},
componentWillUpdate: function() {
console.log('组件2:componentWillUpdate');
},
componentDidUpdate: function() {
console.log('组件2:componentDidUpdate');
},
componentWillUnmount: function() {
console.log('组件2:被卸载:componentWillUnmount');
},
componentWillReceiveProps: function(nextProps) {
console.log('组件2:componentWillReceiveProps:老props:'+this.props.name+';新props:'+nextProps.name);
},
shouldComponentUpdate: function() {
console.log('组件2:shouldComponentUpdate');
return true;
}, render: function () {
return (
<div>
Hello {this.state.name}
</div>
);
}
}); ReactDOM.render(
<Hello name="world"/>,
document.getElementById('example')
); setTimeout(function(){
console.log('修改props重新渲染组件1:');
ReactDOM.render(
<Hello name="world2"/>,
document.getElementById('example')
);
}, 3000) setTimeout(function(){
console.log('初始化渲染新组件2:');
ReactDOM.render(
<Hello2 name="组件2 world2"/>,
document.getElementById('example')
);
}, 6000)
</script>
</body>
</html>

14. React组件样式

React采用行内样式,它接受的必须是一个对象,行如:
style={{display:'none'}}
第一重大括号表示这是 JavaScript 语法,第二重大括号表示样式对象。
说明:
(1)React 行内样式采用驼峰形成,且不支持CSS中的'-'形式表示,如z-index 需写成 zIndex。
(2)浏览器前缀的样式(如-webkit-transition),首字母必须大写,但是ms 开头的例外。

var divStyle = {
color: 'white',
zIndex: 1000,
paddingTop:"10px",
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all', // 注意这里的首字母'W'是大写
msTransition: 'all' // 'ms'是唯一一个首字母需要小写的浏览器前缀
};
React.render(<div style={divStyle}>Hello World!</div>, mountNode);

15. Ajax请求

在实际项目中,我们通常是只把React 用于DOM渲染,而Ajax请求和逻辑判断放在外部JS中。
如果想在React组件中调用Ajax,可以在 componentDidMount 方法中发起 Ajax 请求,等到请求成功,再用 this.setState 方法重新渲染 UI。

    var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
var lastGist = result[0];
if (this.isMounted()) {
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}
}.bind(this));
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
document.body
);

16. getInitialState()
  初始化渲染之前调用(只在第一次渲染时调用,后续重新渲染、修改props/state 都不再调用)。
  所以 getInitialState 中使用props 赋值时,后续重新渲染组件,state 的值将不会被新 props 覆盖。
  getInitialState 的执行早于生命周期中的其他方法。

17. getDOMNode()
  获取 React 组件的 DOM 结构。一般我们会在 componentDidMount 、componentDidUpdate 中使用,用于调用调用第三JS组件(因为第三JS组件都需要DOM结构)。
  参考:http://blog.csdn.net/lihongxun945/article/details/46640225

整理自:http://www.ruanyifeng.com/blog/2015/03/react.html