gpt4 book ai didi

javascript - React JS - 带有函数回调的确认对话框

转载 作者:行者123 更新时间:2023-12-03 00:21:09 28 4
gpt4 key购买 nike

这是我尝试过的,并详细说明了我想要实现的目标,有人可以帮忙吗。

class ConfirmDialog extends React.Component {
callback(action){
alert(action)
}

render(){
return(
<div className='dialog'>
<div>confirm dialog</div>
<button onClick={() => this.callback('yes')}>Yes</button>
<button onClick={() => this.callback('no')}>No</button>
</div>
)
}
}

class Hello extends React.Component {
constructor(props){
super(props);
this.state = {
showDialog: false,
}
}

onButtonClick(params) {
//I want yes no callback here without loosing my previous params
//so i can use switch case here for yes / no action.
this.setState({showDialog: !this.state.showDialog})
}

render() {
return (
<div>
<button onClick={() => this.onButtonClick({test: 'test params'})}>
Click</button>
{
this.state.showDialog ?
<ConfirmDialog callback={this.onButtonClick}/> : null
}
</div>
)
}
}

ReactDOM.render(
<Hello />,
document.getElementById('container')
);
.dialog {
background: tomato;
width: 150px;
height: 150px;
margin: auto;

}

.dialog button {
display : inline-block;
text-align: center;
margin: 0 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>

The on callback function should get which action I clicked and without losing the parameters. React JS - confirmation dialog with function callback with the action without loosing the previous parameter

最佳答案

您没有将 Prop 正确传递给ConfigComponent。您需要使用类构造函数并在 Prop 上调用super

class ConfirmDialog extends React.Component {
constructor(props) {
super(props)
}
callback(action){
alert(action)
}

render(){
return(
<div className='dialog'>
<div>confirm dialog</div>
<button onClick={() => this.props.callback('yes')}>Yes</button>
<button onClick={() => this.props.callback('no')}>No</button>
</div>
)
}
}

现在在您的 Hello 组件中,您可以使用回调的值

class Hello extends React.Component {
constructor(props){
super(props);
this.state = {
showDialog: false,
}
}

onButtonClick(yesOrNo) {
//I want yes no callback here without loosing my previous params
//so i can use switch case here for yes / no action.
console.log(yesOrNo)
this.setState({showDialog: !this.state.showDialog})
}

render() {
return (
<div>
<button onClick={() => this.onButtonClick({test: 'test params'})}>
Click</button>
{
this.state.showDialog ?
<ConfirmDialog callback={this.onButtonClick.bind(this)}/> : null
}
</div>
)
}
}

ReactDOM.render(
<Hello />,
document.getElementById('container')
);

这是工作示例 https://codesandbox.io/s/r09z191w3p

关于javascript - React JS - 带有函数回调的确认对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54310557/

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