阮一峰入门教程
jsx 基本语法规则 遇到 HTML 标签(以 < 开头),就用 HTML 规则解析;遇到代码块(以 { 开头),就用 JavaScript 规则解析
// 组件的使用
class HelloMessage extends React.Component {
constructor(props) {
super(props)
this.state = {
liked: false
}
}
static propTypes = {
title: PropTypes.string.isRequired, // 验证属性
}
static defaultProps = {
name: 'zhorz' // 设置默认属性
}
toggle() {
this.setState({liked: this.state.liked}) // 重新渲染组件
}
render() {
return <h1>hello {this.props.name} <button onClick={this.toggle.bind(this)}>change</button></h1>
// 只能包含一个顶层标签,属性通过 this.props 对象获取
// 通过 this.props.children (可以用React.Children代替) 可以获取组件子节点,vue中使用插槽 solt 实现
}
}
// 注意属性名 class -> className,for -> htmlFor
ReactDOM.render(<HelloMessage name="zhorz"/>, document.getElementById('example'))
// react 获取 dom 的几种方式
class HelloMessage extends React.Component {
handleClick() {
this.refs.my.focus()
}
render() {
return (
<div>
<input type="text" ref="my" />
<input type="button" value="Focus the text input" onClick={this.handleClick.bind(this)} />
</div>
);
}
}
class HelloMessage extends React.Component {
constructor(props) {
super(props)
this.my = React.createRef()
}
handleClick() {
this.my.current.focus()
}
render() {
return (
<div>
<input type="text" ref={this.my} />
<input type="button" value="Focus the text input" onClick={this.handleClick.bind(this)} />
</div>
);
}
}
class HelloMessage extends React.Component {
handleClick() {
this.my.focus()
}
handleClick2 = () => {
this.my.focus() // 使用箭头 函数,这种方式就不用 bind 了,this 指向定义时所在的对象
}
render() {
return (
<div>
<input type="text" ref={(el) => { this.my = el}} />
<input type="button" value="Focus the text input" onClick={this.handleClick2} />
</div>
);
}
}
ReactDOM.render(
<HelloMessage name="zhorz" />,
document.getElementById('example')
);
style={{opacity: this.state.opacity}}
// 因为 React 组件样式是一个对象,所以第一重大括号表示这是 JavaScript 语法,第二重大括号表示样式对象
极客时间demo
create-react-app 模块按需加载
create-react-app 引入组件