gpt4 book ai didi

reactjs - 在 React 组件中处理多个 onChange 回调

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

这就是我目前处理带有两个输入框的场景的方式。作为每个单独的更新方法。这可以/应该使用单个 handleChange 方法来完成吗?

https://codepen.io/r11na/pen/bZKOpj?editors=0011

class App extends React.Component {
constructor(props) {
super(props);

this.handleChange1 = this.handleChange1.bind(this);
this.handleChange2 = this.handleChange2.bind(this);

this.state = {
name1: '',
name2: ''
};
};

handleChange1(e) {
this.setState({
name1: e.target.value
});
};

handleChange2(e) {
this.setState({
name2: e.target.value
});
};

render() {
return (
<div class="row column">
<Label name={this.state.name1}/>
<Input onChange={this.handleChange1} />
<Label name={this.state.name2}/>
<Input onChange={this.handleChange2} />
</div>
);
};
}

const Label = props => (
<p {...props}>Hello: <span className="label-name">{props.name}</span></p>
);

const Input = props => (
<input placeholder="Enter your name" {...props} type="text" />
);

ReactDOM.render(<App />, document.getElementById('app'))

最佳答案

Can/should this be done with a single handleChange method instead?

你可以像这样简化你的代码。

class App extends React.Component {
constructor(props) {
super(props);

this.state = {
name1: '',
name2: ''
};
};

handleChange(e, name) {
this.setState({ [name]: e.target.value });
};

render() {
return (
<div class="row column">
<Label name={this.state.name1}/>
<Input onChange={ (e) => this.handleChange(e, 'name1') } />
<Label name={this.state.name2}/>
<Input onChange={ (e) => this.handleChange(e, 'name2') } />
</div>
);
};
}

Example

<小时/>

感谢@Alik提到eslint规则jsx-no-bind ,

A bind call or arrow function in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.

遵循此规则,您可以更改代码,例如

class App extends React.Component {
constructor(props) {
super(props);

this.onChange = {
name1: this.handleChange.bind(this, 'name1'),
name2: this.handleChange.bind(this, 'name2'),
}

this.state = {
name1: '',
name2: ''
};
};

handleChange(name, event) {
this.setState({ [name]: event.target.value });
};


render() {
return (
<div class="row column">
<Label name={this.state.name1}/>
<Input onChange={ this.onChange.name1 } />
<Label name={this.state.name2}/>
<Input onChange={ this.onChange.name2 } />
</div>
);
};
}

Example

关于reactjs - 在 React 组件中处理多个 onChange 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38633467/

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