我试图在名为 TextInput 的父组件中发生单击时显示下面具有一个输入字段的 SingleLineText 组件。但是,单击后,useState 不会更改状态,因此不会显示名为 SingleLineText 的子组件。
TextInput 组件粘贴在 SingleLineText 组件之后。
SingleLineText 组件:
import React from "react";
const SingleLineText = () => {
return(
<form>
<input />
</form>
)
}
export default SingleLineText;
TextInput 为 SingleLineText 组件的父组件:
import React, {useState, useEffect} from "react";
import SingleLineText from "./SingleLineText"
const TextInput = (props) => {
const [showSingleText, setShowSingleText] = useState(false);
useEffect( () => {
}, [showSingleText])
const handleFieldDisplay = (event) => {
if (event.target.value == "Single line text") {
cancel();
setShowSingleText(showSingleText => !showSingleText);
//setShowSingleText(showSingleText => true);
}
}
const cancel = () => {
props.setShowInput(!props.showInput);
}
return (
<>
<div className="dropdown">
<ul key={props.parentIndex}>
{
props.fieldType.map( (val, idx) => {
return(
<option key={idx} value={val} className="dropdown-item" onClick={handleFieldDisplay}> {val} </option>
)
})
}
</ul>
</div>
{showSingleText && <SingleLineText />}
</>
)
}
export default TextInput;
最顶层或祖父组件:
import React, { useState, useEffect, useRef } from "react"
import PropTypes from "prop-types"
import TextInput from "components/pod_table/fields/inputs/TextInput";
const DynamicFields = (props) => {
const fieldType = ['Checkbox', 'Dropdown', 'boolean', 'Single line text'];
const [showDynamicField, setShowDynamicField ] = useState(false);
const[showInput, setShowInput] = useState(false);
useEffect(() => {}, [showDynamicField, showInput]);
const handleShowDynamicField = (event) => {
setShowDynamicField(!showDynamicField);
}
const handleSubDisplay = (event) => {
if (event.target.value == "customise field type") {
setShowDynamicField(!showDynamicField);
setShowInput(!showInput);
}
}
return (
<React.Fragment>
<div>
<i className="bi bi-chevron-compact-down" onClick={handleShowDynamicField}></i>
{ showDynamicField &&
(<div className="dropdown">
<ul key={props.parentIndex}>
{
optionsHash.map( (val, idx) => {
return(
<option key={idx} value={val} className="dropdown-item" onClick={handleSubDisplay}> {val} </option>
)
})
}
</ul>
</div>) }
{showInput && <TextInput fieldType={fieldType} setShowInput={setShowInput} showInput={showInput} /> }
</div>
</React.Fragment>
)
}
答案 0 :(得分:1)
问题在于,在 handleFieldDisplayFunction
中,您调用了 cancel
函数,该函数更改了父状态 showInput
并因此卸载了 TextInput 组件本身,因此 showSingleText
状态TextInput 组件内部的更改没有任何影响。
以一种无需在单击其中的选项时卸载 TextInput 的方式设计代码
const handleFieldDisplay = (event) => {
if (event.target.value == "Single line text") {
setShowSingleText(showSingleText => !showSingleText);
}
}