我单击输入字段并打开一个模态,我可以在多个选项之间进行选择(基本上是一个风格简约的下拉列表)。
<button id="show">Show</button>
<div id="popup">
Please choose
<button id="option1">1</button>
<button id="option2">2</button>
<button id="option3">3</button>
<button id="option4">Little</button>
<button id="option5">A lot</button>
<button id="option6">A few</button>
</div>
<div id="result"></div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$('#popup').hide();
$('#show').click(function() {
openPopup()
.then(function(data) {
$('#result').html("You pressed " + data)
closePopup();
})
})
function openPopup() {
return new Promise(function(resolve, reject) {
$('#popup').show();
$('#option1').click(function() { resolve('"1"') })
$('#option2').click(function() { resolve('"2"') })
$('#option3').click(function() { resolve('"3"') })
$('#option4').click(function() { resolve('"Little"') })
$('#option5').click(function() { resolve('"A lot"') })
$('#option6').click(function() { resolve('"A few"') })
});
}
function closePopup() {
$('#popup').hide();
}
</script>
到目前为止,我的反应代码是(无聊的部分被删除):
function Modal(){
return (
<div>
<div>
<UnitBlock name="1" />
<UnitBlock name="2" />
<UnitBlock name="3" />
<UnitBlock name="4" />
<UnitBlock name="5" />
</div>
<div>
<UnitBlock name="Little" />
<UnitBlock name="A lot" />
<UnitBlock name="A few" />
</div>
</div>
)
}
function UnitBlock(props) {
return <div className="UnitBlock">{props.name}</div>
}
function FakeInputField(props){
return <div className="FakeInputField">{props.name}</div>
}
function example(){
return(
<div>
<FakeInputField name="Amount"/>
<Modal/>
</div>
)
}
就像在承诺的示例中我尝试创建一些简单的东西,例如&#34;与输入字段交互打开模态,然后单击按钮将其信息发送到输入字段&#34;
答案 0 :(得分:1)
答案 1 :(得分:0)
我认为这类似于: React js onClick can't pass value to method
然而,最简单的解决方案是:
class Modal extends React.Component {
resolve = (val) => { console.log(val); }
render() {
return (
<div>
<div>
<UnitBlock name="1" onClick={() => this.resolve(1)}/>
<UnitBlock name="2" onClick={() => this.resolve(2)}/>
</div>
</div>)
}
}
function UnitBlock(props) {
return <div className="UnitBlock">{props.name}</div>
}
更好的解决方案
https://codesandbox.io/s/p9lk4ooxxq
class UnitBlock extends React.Component {
resolve = (val) => { console.log(val); }
render() {
return <div className="UnitBlock" onClick={
() => this.resolve(this.props.name)}>{this.props.name}</div>
}
}
function UnitBlock(props) {
return (
<div>
<div>
<UnitBlock name="1"}/>
<UnitBlock name="2"}/>
</div>
</div>)
}
}