function Button (props) {
// Returns a DOM element here. For example:
return <button type="submit">{props.label}</button>;
}
// To render the Button component to the browser
ReactDOM.render(<Button label="Save" />, mountNode)
render
function 是重點。Button
function 裡的東西叫 JSX上面的範例也能寫成非 JSX 形式。
function Button (props) {
return React.createElement(
"button",
{ type: "submit" },
props.label
);
}
// To use Button, you would do something like
ReactDOM.render(
React.createElement(Button, { label: "Save" }),
mountNode
);
createElement
function 是 React 7個頂級 API 之一。createElement
? (因為這個值是要 React element,範例中是用 React.createElement()
寫法,也可以用 JSX 寫法 <Button label="Save" />
比較常見。)const RandomValue = () =>
<div>
{ Math.floor(Math.random() * 100) }
</div>;
// To use it:
ReactDOM.render(<RandomValue />, mountNode);
React.Component
是另一個頂級 API。render
function 會回傳一個 button
virtual DOMconstructor
和this
class Button extends React.Component {
render() {
return <button>{this.props.label}</button>;
}
}
// Use it (same syntax)
ReactDOM.render(<Button label="Save" />, mountNode);