猿问

如何在输入中设置来自服务器的值并更改它?

我有这个输入,默认情况下应该有来自服务器的值


              const [nameValue, setNameValue] = useState("");


              <TextField

                id="outlined-read-only-input"

                label="Display Name"

                variant="outlined"

                value={nameValue !== '' ? nameValue : name || '' }

                onChange={(e) => setNameValue(e.target.value)}

                onBlur={() => setName({ variables: { name: nameValue } })} 

              />

名称- 服务器响应


nameValue - 我需要发送到服务器的新值


但是当我尝试更改值并且保留 1 个符号并且我想删除它时,默认返回的值


问题在这里value={nameValue !== '' ? nameValue : name || '' },但我不知道如何解决


export const getMeData = gql`

  query {

    me {

      apsTraining

      backgroundCheck

      city

      contactPreference

      dateOfBirth

      email

      familyCupSignedUp

      gender

      id

      name

      phone

      programWaiver

      state

      stripeEnabled

      zip

    }

  }

`

const { data } = useQuery(getMeData);

const name = data ? data.me.name : null


慕姐4208626
浏览 119回答 2
2回答

犯罪嫌疑人X

由于空字符串("")与null不同,所以nameValue 只能为 null 一次,而一旦nameValue更改,它将始终是一个字符串。&nbsp;const [nameValue, setNameValue] = useState(null);&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; id="outlined-read-only-input"&nbsp; &nbsp; &nbsp; &nbsp; label="Display Name"&nbsp; &nbsp; &nbsp; &nbsp; variant="outlined"&nbsp; &nbsp; &nbsp; &nbsp; value={nameValue !== null ? nameValue : name || ""}&nbsp; &nbsp; &nbsp; &nbsp; onChange={(e) => setNameValue(e.target.value)}&nbsp; &nbsp; &nbsp; &nbsp; onBlur={() => setName({ variables: { name: nameValue } })}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div>&nbsp; );

素胚勾勒不出你

您可以将状态设置为默认名称道具(来自 graphQL)。&nbsp;const [nameValue, setNameValue] = useState(name);&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; id="outlined-read-only-input"&nbsp; &nbsp; &nbsp; &nbsp; label="Display Name"&nbsp; &nbsp; &nbsp; &nbsp; variant="outlined"&nbsp; &nbsp; &nbsp; &nbsp; value={nameValue}&nbsp; &nbsp; &nbsp; &nbsp; onChange={(e) => setNameValue(e.target.value)}&nbsp; &nbsp; &nbsp; &nbsp; onBlur={() => setName({ variables: { name: nameValue } })}&nbsp;&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div>&nbsp; );
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答