gpt4 book ai didi

ReactJS:如何在父组件中创建的子组件中使用EventListener

转载 作者:行者123 更新时间:2023-12-03 13:49:40 25 4
gpt4 key购买 nike

当我有事件监听器时,当我想与 map 中的 child 一起进行一些事件时,我遇到了这个问题。如何在父组件中创建的子组件中使用EventListener?

尝试调整窗口大小:

https://codesandbox.io/s/2j2wnyvln

https://2j2wnyvln.codesandbox.io/

代码正确吗?

最佳答案

您可以使用 Prop 传递事件监听器。
这是example来自documentation (查看 TemperatureInputonTemperatureChange 属性):

// Child
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}

handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}

render() {
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={temperature}
onChange={this.handleChange} />
</fieldset>
);
}
}

// Parent
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
this.state = {temperature: '', scale: 'c'};
}

handleCelsiusChange(temperature) {
this.setState({scale: 'c', temperature});
}

handleFahrenheitChange(temperature) {
this.setState({scale: 'f', temperature});
}

render() {
const scale = this.state.scale;
const temperature = this.state.temperature;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

return (
<div>
<TemperatureInput
scale="c"
temperature={celsius}
onTemperatureChange={this.handleCelsiusChange} />
<TemperatureInput
scale="f"
temperature={fahrenheit}
onTemperatureChange={this.handleFahrenheitChange} />
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

关于ReactJS:如何在父组件中创建的子组件中使用EventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53168343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com