[2018.08.08]
- Render JSX
ReactDOM.render()讲jsx渲染成HTML并插入到指定的DOM节点里。
ReactDOM.render(虚拟节点,真实节点);
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
- Use JavaScript in JSX
在JSX中使用html以(<)作为语法的开头,和html的标签使用方式一样。而JavaScript需写在大括号('{}')里面。
var names = ['Alice', 'Emily', 'Kate'];
ReactDOM.render(
<div>
{
names.map(function (name) {
return <div>Hello, {name}!</div>
})
}
</div>,
document.getElementById('example')
);
- Use array in JSX
var arr = [
<h1>Hello world!</h1>,
<h2>React is awesome</h2>,
];
ReactDOM.render(
<div>{arr}</div>,
document.getElementById('example')
);
- Define a component
通过React.createClass()来创建组件,组件的调用类似于HTML标签的使用,<组件名 />
//创建组件
var test = React.createClass({
render(){
return(
......
)
}
});
- this.props.children
React uses this.props.children to access a component's children nodes.
React.Children 提供了处理 this.props.children 这个不透明数据结构的工具
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.getElementById('example')
);
传送门:
(中文版)https://doc.react-china.org/docs/react-api.html#cloneelement
(英文版)https://reactjs.org/docs/react-api.html#react.children
- PropTypes
Components have many specific attributes which are called ”props” in React and can be of any type
定义react组件的属性的类型(不定义的情况下是任意类型)
var MyTitle = React.createClass({
propTypes: {
title: React.PropTypes.string.isRequired,
},
render: function() {
return <h1> {this.props.title} </h1>;
}
});
The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.
传送门:
(英文版)https://reactjs.org/docs/components-and-props.html
P.S. 用getDefaultProps()来给属性定义一个默认值
var MyTitle = React.createClass({
getDefaultProps : function () {
return {
title : 'Hello World'
};
},
render: function() {
return <h1> {this.props.title} </h1>;
}
});
ReactDOM.render(
<MyTitle />,
document.getElementById('example')
);
(一般情况下,属性props是在组件的调用时候传值进去的)
- Finding a DOM node
Sometimes you need to reference a DOM node in a component. React gives you the ref attribute to find it.
var MyComponent = React.createClass({
handleClick: function() {
this.refs.myTextInput.focus();
},
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')
);
Please be mindful that you could do that only after this component has been mounted into the DOM, otherwise you get null.
- this.state
react通过this.state来保存状态,通过getInitialState()来初始化状态,通过this.setState()来设置更新状态,每一次状态的更新,组件都会重新渲染一次
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')
);
可以通过js的事件来改变react的状态,例如onClick, onKeyDown, onCopy等。
传送门:
(英文)https://reactjs.org/docs/events.html#supported-events
- Form
According to React's design philosophy, this.state describes the state of component and is mutated via user interactions, and this.props describes the properties of component and is stable and immutable.
React的this.state描述了组件的状态,在定义组件的时候,会定义一个初值‘this.state({......})’,可以通过和用户的交互来改变;this.props描述了组件的属性,一般在组件被调用的时候,传入属性和属性值,也可通过''来给组件设定一个默认的属性和值。
和用户的交互有很多种,例如:点击事件,鼠标经过事件等
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.getElementById('example'));
传送门:
https://reactjs.org/docs/forms.html
- Component Lifecycle
组件的生命周期分三部分:
1)安装。被插入DOM结构前,Mounting(being inserted into the DOM);
2)更新。重新渲染,Updating(being re-rendered);
3)卸载。被移除DOM结构,Unmounting(being removed from the DOM)
传送门:
a whole list of lifecycle methods.
var Hello = React.createClass({
getInitialState: function () {
return {
opacity: 1.0
};
},
componentDidMount: function () {
this.timer = setInterval(function () {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
}
this.setState({
opacity: opacity
});
}.bind(this), 100);
},
render: function () {
return (
<div style={{opacity: this.state.opacity}}>
Hello {this.props.name}
</div>
);
}
});
ReactDOM.render(
<Hello name="world"/>,
document.getElementById('example')
);
- Ajax
Using Ajax to fetch data in the event handler of componentDidMount. When the server response arrives, store the data with this.setState() to trigger a re-render of your UI
用ajax在componentDidMount的事件处理程序中获取数据,当响应完后(success),使用this.setState()存储数据来触发组件的重新渲染。
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
var lastGist = result[0];
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.getElementById('example')
);
- Display value from a Promise
异步加载
var RepoList = React.createClass({
getInitialState: function() {
return { loading: true, error: null, data: null};
},
componentDidMount() {
this.props.promise.then(
value => this.setState({loading: false, data: value}),
error => this.setState({loading: false, error: error}));
},
render: function() {
if (this.state.loading) {
return <span>Loading...</span>;
}
else if (this.state.error !== null) {
return <span>Error: {this.state.error.message}</span>;
}
else {
var repos = this.state.data.items;
var repoList = repos.map(function (repo) {
return (
<li>
<a href={repo.html_url}>{repo.name}</a> ({repo.stargazers_count} stars) <br/> {repo.description}
</li>
);
});
return (
<main>
<h1>Most Popular JavaScript Projects in Github</h1>
<ol>{repoList}</ol>
</main>
);
}
}
});
- Server-side rendering
结语:本文大部分内容来自阮一峰大神的博客。
琐碎:store保存初始状态和状态的变化,component里是.jsx文件,存放着各种组件。
传送门:
https://github.com/ruanyf/react-demos#demo02-use-javascript-in-jsx
网友评论