比如在React中经常写
handleChange(e) {
this.setState({value: e.target.value})
}
render() {
return (
<button onClick = {this.handleChange}> add </button>
)
}
this.handleChange就是作为props传递给button组件, 在handleChange中访问父组件,还需要绑定父组件实例
如何为函数绑定父组件实例
ES2015
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {value: 0}
}
handleChange() {
this.setState({value: this.state.value + 1})
}
render() {
return (
<button onClick = {this.handleChange}> add </button>
)
}
在render中绑定
constructor(props) {
super(props)
this.state = {value: 0}
}
handleChange() {
this.setState({value: this.state.value + 1})
}
render() {
return (
<button onClick = {this.handleChange.bind(this)}> add </button>
)
}
在render中使用箭头函数
constructor(props) {
super(props)
this.state = {value: 0}
}
handleChange() {
this.setState({value: this.state.value + 1})
}
render() {
return (
<button onClick = {() => this.handleChange()}> add </button>
)
}
class属性
constructor(props) {
super(props)
this.state = {value: 0}
}
handleChange = () => {
this.setState({value: this.state.value + 1})
}
render() {
return (
<button onClick = {this.handleChange}> add </button>
)
}
根据上面绑定实例如何传递参数给事件处理函数或者回调
在render中绑定
constructor(props) {
super(props)
this.state = {value: 0}
}
handleChange(num) {
this.setState({value: this.state.value + num})
}
render() {
return (
<button onClick = {this.handleChange.bind(this, 2)}> add </button>
)
}
在render中使用箭头函数
constructor(props) {
super(props)
this.state = {value: 0}
}
handleChange(num) {
this.setState({value: this.state.value + num})
}
render() {
return (
<button onClick = {() => this.handleChange(3)}> add </button>
)
}
class属性
这个和在render中绑定比较相似
constructor(props) {
super(props)
this.state = {value: 0}
}
handleChange = (num) => {
this.setState({value: this.state.value + num})
}
render() {
return (
<button onClick = {this.handleChange(4)}> add </button>
)
}
还有一种通过data-attributes 传递参数
constructor(props) {
super(props);
this.state = {
value: 0,
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
};
}
handleClick2(letter) {
this.setState({ value: letter });
}
render() {
return (
<p>value: {this.state.value}</p>
<ul>
{this.state.letters.map(letter =>
<li key={letter} onClick={() => this.handleClick2(letter)}>
{letter}
</li>
)}
</ul>
)
}