class CommentBox extends Component {
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList />
<CommentForm />
</div>
);
}
}
受控组件:表单元素状态由使用者维护
<input type="text"
value={this.state.value}
onChange={evt =>
this.setState({value: evt.target.value})
}
/>
非受控组件:表单元素状态由 DOM 自身维护
<input type="text"
ref={node => this.input = node}
/>
单一职责原则:
DRY 原则:
const name = 'Cell';
const element = (
<h1>
Hello, {name}
</h1>
);
const name = 'Cell';
const element = React.createElement(
'h1',
null,
'Hello, ',
name
);
在 JSX 中使用表达式
const element = <h1>Hello, world</h1>
<MyComment foo={ 1+2 } />
const props = {
firstName: 'Cell',
lastName: 'Lin',
};
const greeting = <Greeting {...props} />;
const element = <h1>{props.firstName}</h1>
JSX 优点
JSX 约定
div
<menu.Item />
Virtual DOM 是 JSX 运行的基础。
高阶组件接受组件作为参数,返回新的组件。可以通过高阶组件协调外部资源。
const EnhancedComponent = higherOrderComponent(WrappedComponent);
class MyComment extends React.Component {
render () {
return (
<div>
{this.props.children('cellinlab')}
</div>
);
};
}
<MyComment>
{(name) => <div>Hello, {name}</div>}
</MyComment>
用于共享全局状态。
const ThemeContext = React.createContext('light');
class App extends React.Component {
render () {
return (
<ThemeContext.Provider value='dark'>
<ThemeButton />
</ThemeContext.Provider>
);
}
}
function ThemeButton(props) {
return (
<ThemeContext.Consumer>
{(theme) => <Button {...props} theme={theme} />}
</ThemeContext.Consumer>
);
}
create-react-app (opens new window)