获取文本输入值反应

时间:2021-04-21 14:21:26

标签: javascript reactjs

我正在尝试使用状态跟踪文本输入值,但“e.target.value”似乎不起作用(可能是因为我的组件被声明为函数)。有没有其他办法可以做到?

const UncontrolledDiagram = ({ sentence }) => {
  // create diagrams schema

  const [schema, { onChange, addNode, connect, removeNode }] = useSchema(initialSchema);

  const [selected, setSelected] = useState([]);

  const [textInput,setInput]=useState('')
  
  const handleTextChange=(e)=>{
    setInput(e.target.value);
    console.log(textInput);
  }

这是我正在跟踪的输入字段:

const conditionalDisplay=(id)=>{
    const nodeToCheck=schema.nodes.find(node=>node.id=== id);
    if(nodeToCheck.form===null){
      return(
        <div>
          <label>Form: </label><input style={{ width: '25px', height: '12px' }} onChange={handleTextChange} type='text'></input>
          <button className='buttonInputSubmit'>+</button>
        </div>
      )
    }
    else{
      return(
        <div style={{display: 'flex',margin: '0'}}>
          <label>Form: </label><p style={{color: 'yellow', marginLeft:'2px'}}>{nodeToCheck.form}</p>
        </div>
      )
    }
  }

1 个答案:

答案 0 :(得分:1)

它有效,您的 console.log(textInput) 仍然具有旧状态,因为状态是异步设置的。它会在您的函数完全执行后立即设置状态。

const handleTextChange=(e)=>{
   setInput(e.target.value);
}

useEffect(() => {
    console.log(textInput);
}, [textInput])