React 笔记4:Components and Props
Functional and Class Components
function Welcome(props) {
return <h1>Hello,{props.name}</h1> }
class Welcome extends React.Component {
render() {
return <h1>Hello,{this.props.name}</h1>
}
}
Rendering a Component(渲染组件)
const element = <div />;
const element = <Welcome name="Sara"/>
function Welcome(props) {
return <h1>Hello,{props.name}</h1> } const element = <Welcome name="Sara"/> ReactDOM.render( element,document.getElementById('root') );
Composing Components(组件构成)
function Welcome(props) {
return <h1>Hello,{props.name}</h1> } function App() { return ( <div> <Welcome name = "Sara" /> <Welcome name = "Cahal" /> <Welcome name = "Edite" /> </div> ); } ReactDOM.render( <App />,document.getElementById('root') );
Extracting Components (提取组件)
function Comment(props) {
return (
<div className="Comment"> <div className="UserInfo"> <img className="Avatar" src={props.author.avatarUrl} alt={props.author.name}/> <div className="UserInfo-name">{props.author.name}</div> </div> <div className="Comment-text">{props.text}</div> <div className="Comment-date">{formatDate(props.date)}</div> </div> ); }
function Avatar(props) {
return (
<img className="Avatar" src=props.user.avatarUrl} alt={prop.user.name} /> ); }
function Comment(props) {
return (
<div className="Comment"> <div className="UserInfo"> <Avatar user={props.author} /> <div className="UserInfo-name">{props.author.name}</div> </div> <div className="Comment-text">{props.text}</div> <div className="Comment-date">{formatDate(props.date)}</div> </div> ); }
function UserInfo(props) {
return (
<div className="UserInfo"> <Avatar user={props.user} /> <div className="UserInfo-name"> {props.user.name} </div> </div> ); }
function Comment(props) {
return (
<div className="Comment"> <UserInfo user={props.author} /> <div className="Comment-text">{props.text}</div> <div className="Comment-date">{formatDate(props.date)}</div> </div> ); }
Props are Read-Only
function sum(a,b) {
return a+b;
}
function(account,amount) {
account.total -= amount;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |