1、JSX: 一种JavaScript的语法扩展
JSX 代表Objects --> Babel 会将JSX转化成React.createElement()方法调用
const element = (<h1 className='greeting'>Hello,world!</h1>);
--(Babel)编译--> const element = React.createElement('h1',{className: 'greeting'},'Hello,world');
---返回值--> const element = {type: 'h1',props: {className: 'greeting',children:'Hello,world'}}( 该返回对象称为 --> React 元素)
2、元素渲染
React 只会更新改变了的部分。
React 元素都是immutable 不可变的。更新界面的唯一办法是创建一个新的元素,然后将它传入 ReactDOM.render() 方法。
React 元素可以是DOM标签,也可以是用户自定义的组件。
function tick(){
const element = (<div>
<h1>Hello,world!</h1>
<h2>It is {new Date().toLocaleTimeString()}</h2>
</div>
);
ReactDOM.render(element,document.getElementById('root'));
}
3、组件 & Props
组件名称必须以大写字母开头。
组件的返回值只能有一个根元素(用一个<div>来包裹所有<Welcome />元素的原因)。
组件内只有rander(),没有局部状态,可以用函数定义组件。
props: 属性的 json 对象,它是只读的,不能修改本身
3.1 组合组件
function Welcome(props) { // props --> {name: 'Sara'}
return <h1>Hello,{proos.name}</h1>;
}
function App() {
return (<div>
<Welcome name='Sara' />
<Welcome name='Cale' />
<Welcome name='Andy' />
</div>);
}
React.render(
<App />,
document.getElementById('root')
);
3.2 提取组件
原始组件:
function formatDate(date) {
return date.toLocaleDateString();
}
function Comment(props) {
return (<div className='Comment'>
<div className='UserInfo'>
<img className='Avatar' src={props.author.avatarUrl} alt={props.autuor.name}/>
<div className='UserInfo-name'>{props.autuor.name}</div>
</div>
<div className='Comment-text'>{props.text}</div>
<div className='Comment-date'>{formatDate(props.date)}</div>
</div>);
}
const comment = {
author: {name: 'Hello Kitty', avatarUrl: 'http://placekitten.com/g/64/64'},
text: 'I hope you enjoy learning React!',
date: new Date()
};
React.render(
<Coment
author={comment.author} text={comment.text} date={comment.date} />,
document.getElementById('root');
);
提取组件(原则:逐层从外部到内部提取)
function formatDate(date) {
return date.toLocaleDateString();
}
//提取二:
function Avatar(props) {
return (<img className='Avatar' src={props.user.avatarUrl} alt={props.user.name}/>);
}
// 提取一:
function UserInfo(props) {
return (<div className='UserInfo'>
<img 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>);
}
const comment = {
author: {name: 'Hello Kitty', avatarUrl: 'http://placekitten.com/g/64/64'},
text: 'I hope you enjoy learning React!',
date: new Date()
};
React.render(
<Coment
author={comment.author} text={comment.text} date={comment.date} />,
document.getElementById('root');
);