【问题标题】:Cannot Keep My Text Inside State By Click a Button无法通过单击按钮将我的文本保持在状态
【发布时间】:2021-02-17 07:09:42
【问题描述】:

我有这样的反应代码

const { useState, useEffect } = React;
const { TextField, Button } = MaterialUI;

const Example = props => {
  const [myText, setMyText] = useState("default text")

  useEffect(() => {
    console.log("my text is :", myText)
  }, [myText])

  return (
    <div style={{ flex: 1, flexDirection: 'column'}}>
      <TextField
        label="Text"
        fullWidth
        type="text"
        defaultValue={myText}
        onChange={e => {
          console.log('text: ', e.currentTarget.value);
          setMyText(e.target.value);
        }}
      />
      <Button onClick={() => console.log("SUBMIT TEXT :", myText)}>SUBMIT MY NAME</Button>
    </div>
  )
}

ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://unpkg.com/react@17.0.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@4.11.3/umd/material-ui.production.min.js"></script>
<div id="root"></div>

我尝试输入我的文本"Hello World"useEffect 触发并且工作正常,就像我的输入文本一样,但是在我单击submit button 后,文本恢复为默认的“默认文本”

像这样

当我点击按钮时如何保留我的输入文本?

【问题讨论】:

  • 您不是在调用setMyText,而是在调用setText,这根本不在您的代码中。此外,您可能想要value={myText},而不是defaultValue={...}
  • 是的,我的代码有点错误,我更新了我的代码
  • 当我使用value={myText}时,我的文本字段在输入时不会更新,所以我使用defaultValue={...}
  • 什么是&lt;TextField&gt;?这应该适用于常规 &lt;input value={myText} onChange={e =&gt; setMyText(e.target.value)} /&gt;
  • 我刚刚创建了一个堆栈 sn-p 并没有重现您描述的问题。投票结束,因为不可复制。

标签: reactjs react-hooks state


【解决方案1】:
import { Button, TextField } from "@material-ui/core";
import React from "react";

const Example = (props) => {
  const [myText, setMyText] = React.useState("");
  const [value, setValue] = React.useState("default text");
  
  return (
    <div style={{ flex: 1, flexDirection: "column" }}>
      <h1> {value} </h1>
      <TextField placeholder="Default" label="Enter Name" type="text" defaultValue={myText}
                 onChange={(e) => {setMyText(e.target.value)}}/>
      <br/>
      <Button style={{ marginTop: "20px" }} variant="contained" color="primary"
              onClick={() => setValue(myText)}>
        SUBMIT MY NAME
      </Button>
    </div>
  );
};

ReactDOM.render(<Example />, document.getElementById('root'));

【讨论】:

    【解决方案2】:

    我认为当您单击从材料中导入的按钮时,按钮的类型是提交,因此它将刷新您的页面并且状态恢复为默认值。

    您可以通过在组件加载时添加 useEffect 方法来测试这一点。

    useEffect(()=> console.log('page was refreshed') , [])
    

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 1970-01-01
      • 2014-01-04
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2017-12-25
      相关资源
      最近更新 更多