ReactDOM.render()
ReactDOM.render(
<h1>Hello,world</h1>,
document.getElementById('example')
);
取到某一個dom,然后把上面的html放至dom中
JSX語法
var names = ['Alice', 'Emily', 'Kate'];
ReactDOM.render(
<div>
{
names.map(function (name) {
return <div>Hello, {name}</div>
});
}
<div>,
document.getElementById('example')
);
JSX允許直接在模板中插入JS變量,如果這個變量是一個數(shù)組,則會展開這個數(shù)組的所有成員
var arr = [
<h1>Hello world</h1>
<h2>React is awesome</h2>
];
ReactDOM.render(
<div>{arr}</div>
document.getElementById('example');
);
組件
React允許將代碼封裝成組件(componet), 像插入普通的HTML標簽一樣,在網(wǎng)頁中插入這個組件,React.createClass 方法就用于生成一個組件類
var HelloMessage = React.createClass({
render: function () {
return <h1>Hello {this.props.name}</h1>
}
});
ReactDOM.render(
<HelloMessage name="John" />
document.getElementById('example')
);
注意: 組件一個字母必須大寫,組件只能包含一個頂層標簽
組件的屬性可以再組件類的this.props對象上獲取,比如name屬性就可以通過this.props.name 讀取。
注意
添加屬性的時候
class屬性需要改成 className
for屬性要改成 htmlFor
this.props.children
this.props對象的屬性與組件的屬性一一對應,但是有個例外,就是this.props.children 屬性,他表示組件的所有子節(jié)點
var NoteList = React.createClass({
render: function () {
return (
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>
})
);
}
});
ReactDOM.render(
<NoteList>
<span>HELLO</span>
<span>world</span>
</NoteList>
);
this.props.children 的值有三種可能:
1、當前組件沒有節(jié)點 就是 undefined
2、當前組件只有一個節(jié)點,數(shù)據(jù)類型就是 object
3、如果有多個子節(jié)點, 數(shù)據(jù)類型就是array
對于這種情況,React提供了一個方法, React.Children 來處理 this.props.children => 可以用React.Children.map來遍歷子節(jié)點,不需要擔心 this.props.children 的數(shù)據(jù)類型是哪種
PropTypes
var MyTitle = React.createClass({
propTypes: {
title: React.PropTypes.string.isRequired,
},
render: function () {
return <h1>{this.props.title}</h1>
}
});
組件類的propTypes屬性,就是用來驗證組件實例的屬性是否符合要求
var data = 123;
ReactDOM.render(
<MyTitle title={data} />
document.body
);
getDefaultProps 可以設置組件屬性的默認值
獲取真正的DOM節(jié)點
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')
);
React.Component
ES6
class Greeting extends React.component {
render () {
return <h1>Hello, {this.props.name}</h1>
}
}
var CommentList = React.createClass({
render: function () {
return (
<div className="commentList">
Hello
</div>
);
}
});
HTML組件是正常的React組件,就和定義的一樣,JSX編譯器會自動重寫HTML標簽為 React.createElement(tagName);