React prevstate usage



我有一个Cell组件,当我点击它时,我希望出现一个名为ChangeParamWindow的弹出窗口。CCD_ 3有2个按钮,如果点击了其中任何一个,我想刷新CCD_;如果是block(用于隐藏块(,则ChangeParamWindow将其显示改变为none。它只成功地隐藏了一次,但再也没有。我很确定使用prevState在某种程度上是错误的,但abybody能告诉我我做错了什么吗?

class ChangeParamWindow extends React.Component {
constructor(props) {
super(props)
this.onClose = this.onClose.bind(this);
this.state = {
placeholder: "Param...",
maxlength  : 100,
inputType  : "text",
type       : "any",  // number or string. (for restritions)
value      : null,
outline    : "none",
position   : "absolute",
display    : "block"
}
this.inputId = "small-window-input-id"
}
onClose(e) {
e.preventDefault()
let value = document.getElementById(this.inputId).value
console.log("new value is", value)
this.setState(prevState => ({
display : (prevState.display == "none") ? "display" : "none", // TODO ???
value   : value
}))
}
render(){
return (
<div
style={{
display  : this.state.display,
position : this.state.position,
outline  : this.state.outline,
left     : this.props.x,
top      : this.props.y
}}
>
<input
id={this.inputId}
maxLength={this.state.maxlength}
type={this.state.inputType}
placeholder={this.state.placeholder}
/>
<input
onClick={ this.onClose }
type="submit"
value="ok"
/>
<input
onClick={this.onClose }
type="submit"
value="cancel"
/>
</div>
)
}
}
class Cell extends React.Component {
constructor(props) {
super(props)
this.state = {
value   : null,
type    : "any",
noValue : "..."
}
}
openChangeParamWindow(x, y) {
ReactDOM.render(
<ChangeParamWindow
x={x}
y={y}
/>,
document.getElementById("change-param-window")
)
}
isNumberValid() {
}
isStringValid() {
}
render() {
let value = (this.state.value == null) ? this.state.noValue : this.state.value;
return (
<div
className="cell"
onClick={event => {
this.openChangeParamWindow(event.clientX, event.clientY)
}}
>
{value}
</div>
);
}
}
ReactDOM.render(
<Cell />,
document.getElementById('init-cell')
);
.cell {
background:grey;
border-radius: 7px;
border:0;
transition: 0.25s;
width:40px;
height:25px;
text-align: center;
padding-top:5px;
}
.cell:hover {
cursor: pointer;
background:white;
}
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="change-param-window"></div>
<div id="init-cell"></div>

您几乎肯定不想在这里使用ReactDOM.render两次。您应该使用ReactDOM.render渲染应用程序的根组件,但在此之后,如果您想渲染组件树层次结构之外的内容,则需要使用React Portals。这里的医生应该会帮你解决问题。如果你还需要帮助,我可以深入了解。

最新更新