【问题标题】:How to configure 'value' in the input field in React?如何在 React 的输入字段中配置“值”?
【发布时间】:2022-01-01 02:51:09
【问题描述】:

在 React 中,我有一个带有提交按钮的文本框,该按钮在用户单击“向我挥手”时可见,而在用户单击“提交”后不可见。我在输入标签中放置了什么值?如果我可以在 setFormText 方法中使用它,我该如何获得价值?在组件类中,值在下面,但功能代码的等价物是什么?

<input type="text" value={this.state.value} onChange={this.handleChange} />

我的代码在默认的 App() 函数中,目前用户无法更改文本:

const [currentVisibility, setVisibility] = useState(false);
const [currentFormText, setFormText] = useState("");

//wave at me button just shows the form
const wave = async () => {
    setVisibility(true);
    console.log("form appears")
  }

// I don't think it's correct to use changeValue function

  const changeValue = async () => {
    console.log("formed had some text");
  }

  const handleChange = async () => {
    console.log("form was changed");
  }

//the handle submit should read the value from the input field to use in the parameter string of the wave() function. 
  const handleSubmit = async () => {
    try {
      setVisibility(false);
      const { ethereum } = window;

      if (ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();
        const wavePortalContract = new ethers.Contract(contractAddress, contractABI, signer);

        let count = await wavePortalContract.getTotalWaves();
        console.log("Retrieved total wave count...", count.toNumber());

        //change to currentText instead of water bottle
        const waveTxn = await wavePortalContract.wave("water bottle");
        console.log("Mining...", waveTxn.hash);

        await waveTxn.wait();
        console.log("Mined -- ", waveTxn.hash);

        count = await wavePortalContract.getTotalWaves();
        console.log("Retrieved total wave count...", count.toNumber());

      } else {
        console.log("Ethereum object does not exist!");
      }
    } catch (error) {
      console.log(error)
    }
  }
return {currentVisibility && (

          <form onSubmit={handleSubmit}>
            <label>
              Message:
          <input type="text" value="" onChange={handleChange} />
            </label>
            <input type="submit" value="Submit" />
          </form>
        )}

【问题讨论】:

    标签: reactjs react-hooks solidity


    【解决方案1】:

    useState 钩子返回状态值和一个 setter 函数。因此,在您的情况下,currentFormText 是状态值,setFormText 是设置器函数。因此,您的输入应为:

    <input type="text" value={currentFormText} onChange={handleChange} />
    

    如果您这样做,您会注意到您无法更改输入的值。那是因为 React 现在是 "controlling" 的输入值;换句话说,React 现在是这个输入的“真实来源”(而不是浏览器/HTML 本身)。因此,您需要添加到处理函数:

    // we certainly don't need the `async` keyword here!
    const handleChange = (event) => {
        console.log("form was changed");
        setFormText(event.target.value);
    }
    

    【讨论】:

      【解决方案2】:
      1. 在表单提交刷新页面时,需要将此代码e.preventDefault();放入handleSubmitfunction中!

      2. handleChange 函数调用时需要将输入值设置为currentFormText 状态,这就是您无法更改文本的原因!

      试试这个代码,它对我有用

      function App() {
        const [currentVisibility, setVisibility] = useState(true);
        const [currentFormText, setFormText] = useState("");
      
        //wave at me button just shows the form
        const wave = async () => {
          setVisibility(true);
          console.log("form appears")
        }
      
        const changeValue = async () => {
          console.log("formed had some text");
        }
      
        const handleChange = async (value) => {
          setFormText(value)
          console.log("form was changed");
        }
      
        //the handle submit should read the value from the input field to use in the parameter string of the wave() function. 
        const handleSubmit = async (e) => {
          try {
            e.preventDefault();
            setVisibility(false);
            const { ethereum } = window;
      
            if (ethereum) {
              const provider = new ethers.providers.Web3Provider(ethereum);
              const signer = provider.getSigner();
              const wavePortalContract = new ethers.Contract(contractAddress, contractABI, signer);
      
              let count = await wavePortalContract.getTotalWaves();
              console.log("Retrieved total wave count...", count.toNumber());
      
              //change to currentText instead of water bottle
              const waveTxn = await wavePortalContract.wave("water bottle");
              console.log("Mining...", waveTxn.hash);
      
              await waveTxn.wait();
              console.log("Mined -- ", waveTxn.hash);
      
              count = await wavePortalContract.getTotalWaves();
              console.log("Retrieved total wave count...", count.toNumber());
      
            } else {
              console.log("Ethereum object does not exist!");
            }
          } catch (error) {
            console.log(error)
          }
        }
      
        return (
          currentVisibility &&
          <form onSubmit={(e) => handleSubmit(e)}>
            <label>
              Message:
              <input type="text" value={currentFormText} onChange={(e) => handleChange(e.target.value)} />
            </label>
            <input type="submit" value="Submit" />
          </form>
        )
      }
      
      
      export default App;
      

      【讨论】:

        猜你喜欢
        • 2019-09-30
        • 1970-01-01
        • 1970-01-01
        • 2020-10-06
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多