gpt4 book ai didi

javascript - 具有多个setstate的React js单个函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:50 25 4
gpt4 key购买 nike

按钮组件(子)

export default class Button extends React.Component {
render() {
var handleToUpdate = this.props.handleToUpdate;
return (
<button onClick={() => handleToUpdate(this.id)}>
{this.props.title}
</button>
);
}
}

索引(父级)
作为返回

<Button title={title1} handleToUpdate={handleToUpdate.bind(this)} />
<Button title={title2} handleToUpdate={handleToUpdate1.bind(this)} />
<Button title={title3} />
<Button title={title4} />

渲染

const title1 = "test1"
const title2 = "test2"
const title3 = "test3"
const title4 = "test4"
var handleToUpdate = this.handleToUpdate;
var handleToUpdate1 = this.handleToUpdate1;

函数

  handleToUpdate() {
this.setState({})
}

handleToUpdate1() {
this.setState({})
}

var handleToUpdate = this.handleToUpdate.bind(this);
var handleToUpdate1 = this.handleToUpdate1.bind(this);

我的代码没有问题,但我认为我处理函数的方式不是好的做法。

我在这里做的是制作按钮组件(子组件)并在父组件(索引)中调用它四次。我创建了 onClick Prop 来调用函数,然后设置状态。

有没有其他方法可以让我用 4 个 setState 创建一个函数并根据单击的按钮 ID 调用状态。

让它更清晰。

点击按钮 1 => 调用 singlefunction => setstate1

点击按钮 2 => cal singlefunction => setstate 2...

最佳答案

如果您将 id 传递给 Button 组件,这里是另一种方法。

const buttons = [
{ id: 1, title: "test1" },
{ id: 2, title: "test2" },
{ id: 3, title: "test3" },
];

class App extends React.Component {
state = {
clicked: "",
};

onUpdate = ( id ) => {
this.setState( { clicked: id } );
};

render() {
console.log( this.state );
return (
<div>
{buttons.map( button => (
<Button
key={button.id}
button={button}
onUpdate={this.onUpdate}
/>
) )}
</div>
);
}
}

const Button = ( props ) => {
const { button, onUpdate } = props;
const handleUpdate = () => onUpdate( button.id );
return <button onClick={handleUpdate}>{button.title}</button>;
};

ReactDOM.render( <App />, document.getElementById( "root" ) );
<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>
<div id="root"></div>

关于javascript - 具有多个setstate的React js单个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52750693/

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