如何从状态设置输入的值(React应用程序)

发布于 2025-01-17 12:55:21 字数 1748 浏览 2 评论 0 原文

我希望从我从道具中获得的州设置输入价值!我可以从占位符中的“配置文件”状态设置所有信息,但是将其放在值字段中时,它没有显示任何信息。这是我的代码和我使用的表格:

<Form
    name="basic"
    wrapperCol={{ span: 24 }}
    onFinish={onUpdate}
    onFinishFailed={onFinishFailed}>
    <FormItem>
        <Input prefix={<ContactsTwoTone />} placeholder={profile.name} />
    </FormItem>

    <FormItem name="email"
        rules={[
            {
                type: 'email',
                message: 'The input is not valid E-mail!',
            }
        ]}
    >
        <Input value={profile.email} name="name" prefix={<MailTwoTone />} placeholder={profile}  />
    </FormItem>
    <FormItem name="mobile" value={profile.mobile} >
        <Input value={profile.mobile} name="mobile" prefix={<PhoneTwoTone />} placeholder={profile.mobile} />
    </FormItem>
    <FormItem name="addres">
        <Input name="addres" prefix={<HomeTwoTone />} placeholder={profile.addres} />
    </FormItem>
    <FormItem name="description">
        <Input.TextArea name="description" placeholder="description" rows={4} prefix={<ContainerTwoTone />} />
    </FormItem>
    <FormItem>
        <Button className="width-100" type="primary" htmlType="submit" onClick={onUpdate} >Update</Button>
    </FormItem>
</Form> 

使用效果函数和状态声明:

const [visible, setVisible] = useState(false);
const FormItem = Form.Item;
const [profile, setProfile] = useState({});

useEffect(() => {
    setProfile(props.profile); 
}, [props.profile]);

const showDrawer = () => {
    setVisible(true);
}; 

I am looking to set the value of Input from the state that I receive from props! I could set all the information from "profile" state in the placeholder but when putting it in the value field it doesn't show anything. Here's my code and the form I use :

<Form
    name="basic"
    wrapperCol={{ span: 24 }}
    onFinish={onUpdate}
    onFinishFailed={onFinishFailed}>
    <FormItem>
        <Input prefix={<ContactsTwoTone />} placeholder={profile.name} />
    </FormItem>

    <FormItem name="email"
        rules={[
            {
                type: 'email',
                message: 'The input is not valid E-mail!',
            }
        ]}
    >
        <Input value={profile.email} name="name" prefix={<MailTwoTone />} placeholder={profile}  />
    </FormItem>
    <FormItem name="mobile" value={profile.mobile} >
        <Input value={profile.mobile} name="mobile" prefix={<PhoneTwoTone />} placeholder={profile.mobile} />
    </FormItem>
    <FormItem name="addres">
        <Input name="addres" prefix={<HomeTwoTone />} placeholder={profile.addres} />
    </FormItem>
    <FormItem name="description">
        <Input.TextArea name="description" placeholder="description" rows={4} prefix={<ContainerTwoTone />} />
    </FormItem>
    <FormItem>
        <Button className="width-100" type="primary" htmlType="submit" onClick={onUpdate} >Update</Button>
    </FormItem>
</Form> 

The useEffect function and the declaration of state:

const [visible, setVisible] = useState(false);
const FormItem = Form.Item;
const [profile, setProfile] = useState({});

useEffect(() => {
    setProfile(props.profile); 
}, [props.profile]);

const showDrawer = () => {
    setVisible(true);
}; 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

守不住的情 2025-01-24 12:55:21

我希望从我收到的状态中设置输入的价值
从道具!

如果您只是想从状态设置输入,这是一个简单的示例。

解决方案和演示

https://codesandbox.io/p/devbox/1q0ftq

import { useState } from "react";

const initialValue = "John";

const App = () => {
  const [name, setName] = useState(initialValue);

  console.log("state: ", name);

  const handleChange = (event) => {
    const value = event.target.value;
    setName(value);
  };

  return (
    <div>
      <h2>Form</h2>
      <pre>Type in the input...</pre>
      <form>
        <input type="text" onChange={handleChange} value={name} />
      </form>
      <pre>state: {name}</pre>
    </div>
  );
};

export default App;

您的问题和示例代码,似乎您可能会认为Prop应该根据您的使用效果告知某些新状态。

这里有几个问题。您在 useffect 中包括一个道具作为依赖关系。这是多余的,因为当道具发生变化时,反应已经触发了重新渲染。因此,使用效果在此处不需要或适用。新值将通过道具可用。我们可以在组件中简单地使用它,知道道具是最新的。这使问题更加简单。

您似乎本质上是在询问如何将道具传递到您的形式中。以下是用于管理配置文件状态的可编辑档案部分的示例。表单部分只需读取状态的值并显示配置文件信息。这说明了您描述的所需行为。表单只是接收档案状态作为道具传递的配置文件状态的组件。

配置文件字段依靠状态来实现其价值。表单组件依赖于基于该状态的道具。

Example Passing Props to Component

https://codesandbox.io/p/devbox/dawn-cloud -sbxmoz

import { useState } from "react";

const initialProfile = {
  firstName: "John",
  lastName: "Doe"
};

const Form = ({ firstName, lastName }) => (
  <div>
    <h2>Form</h2>
    <pre>Values based on profile...</pre>
    <form>
      <input
        label="First Name"
        type="text"
        name="firstName"
        value={firstName}
      />
      <input label="Last Name" type="text" name="lastName" value={lastName} />
    </form>
  </div>
);

const App = () => {
  const [profileFields, setProfileFields] = useState(initialProfile);

  const { firstName, lastName } = profileFields;

  console.log("profile fields: ", profileFields);

  const handleChange = (event) => {
    const { name, value } = event.target;
    setProfileFields(() => {
      return {
        ...profileFields,
        [name]: value
      };
    });
  };

  return (
    <div>
      <Form firstName={firstName} lastName={lastName} />
      <h2>Profile</h2>
      <pre>Type to edit profile fields...</pre>
      <form>
        <input
          label="First Name"
          type="text"
          onChange={handleChange}
          name="firstName"
          value={firstName}
        />
        <input
          label="Last Name"
          type="text"
          onChange={handleChange}
          name="lastName"
          value={lastName}
        />
      </form>
    </div>
  );
};

export default App;

说明和资源

示例中的 ,您可以在配置文件字段中键入以查看如何通过道具更新表单值。在顶部形式中键入不会更新值,因为这些值是只读的,并且“从道具设置”。

您可能不需要仅阅读表格,但这仅基于您的示例。您可以将个人资料数据作为道具传递给任何需要的组件。

我认为我希望在这里沟通的想法是考虑您的个人资料数据(您的状态)的“真实性来源”,并根据需要使用的其他组件来确定您想要在哪里生活。

这通常称为受控不受控制的组件。该概念通常带有表单输入,因为用React状态控制表单对于作为用户类型访问和验证输入非常有用,使用传统方式使用HTML输入可以实现。

资源

希望这会有所帮助。

I am looking to set the value of Input from the state that i receive
from props!

If you're just looking to set the input from state, here is a simple example of that.

Solution and Demo

https://codesandbox.io/p/devbox/1q0ftq

import { useState } from "react";

const initialValue = "John";

const App = () => {
  const [name, setName] = useState(initialValue);

  console.log("state: ", name);

  const handleChange = (event) => {
    const value = event.target.value;
    setName(value);
  };

  return (
    <div>
      <h2>Form</h2>
      <pre>Type in the input...</pre>
      <form>
        <input type="text" onChange={handleChange} value={name} />
      </form>
      <pre>state: {name}</pre>
    </div>
  );
};

export default App;

Regarding the rest of your question and the example code, it looks like you may be thinking that props should inform some new state based on your useEffect.

There are a couple issues here. You included a prop as a dependency in your useEffect. This is redundant because when props change, React already triggers a re-render. So, useEffect isn't necessary or applicable here. The new value will be available via props already. We can simply use it in our component, knowing that props are up-to-date. This makes the problem much more straightforward.

You seem to essentially be asking about how to pass props into your form. Below is an example with editable profile section that is used to manage the profile state. The form section simply reads the values from state and displays the profile information. This illustrates the desired behavior you're describing. The form is just a component that receives the profile state passed down as props.

The profile fields rely on state for their values. The form component relies on props based on that state.

Example Passing Props to Component

https://codesandbox.io/p/devbox/dawn-cloud-sbxmoz

import { useState } from "react";

const initialProfile = {
  firstName: "John",
  lastName: "Doe"
};

const Form = ({ firstName, lastName }) => (
  <div>
    <h2>Form</h2>
    <pre>Values based on profile...</pre>
    <form>
      <input
        label="First Name"
        type="text"
        name="firstName"
        value={firstName}
      />
      <input label="Last Name" type="text" name="lastName" value={lastName} />
    </form>
  </div>
);

const App = () => {
  const [profileFields, setProfileFields] = useState(initialProfile);

  const { firstName, lastName } = profileFields;

  console.log("profile fields: ", profileFields);

  const handleChange = (event) => {
    const { name, value } = event.target;
    setProfileFields(() => {
      return {
        ...profileFields,
        [name]: value
      };
    });
  };

  return (
    <div>
      <Form firstName={firstName} lastName={lastName} />
      <h2>Profile</h2>
      <pre>Type to edit profile fields...</pre>
      <form>
        <input
          label="First Name"
          type="text"
          onChange={handleChange}
          name="firstName"
          value={firstName}
        />
        <input
          label="Last Name"
          type="text"
          onChange={handleChange}
          name="lastName"
          value={lastName}
        />
      </form>
    </div>
  );
};

export default App;

Explanation and Resources

In the example, you can type in the profile fields to see how the form values are updated via props. Typing in the top form won't update values because these are read-only and "set from props".

You might not want a read-only form, but this is just based on your example. You can pass your profile data as props to whatever component needs it.

I think the idea I'm hoping to communicate here is to think about a "single source of truth" for your profile data (your state) and decide where you want that to live depending on what other components need to use it.

This is commonly referred to as controlled versus uncontrolled components. The concept comes up often with form inputs since controlling the form with React state is very useful for accessing and validating inputs as a user types, which isn't easily achievable using HTML inputs in the traditional way.

Resources

https://react.dev/learn/sharing-state-between-components#controlled-and-uncontrolled-components

Hopefully that helps.

旧人 2025-01-24 12:55:21

尝试将他们注销,看看他们是否正在做他们应该做的事情。

const SomeInput = (props) => {
  const { name, placeholder, value } = props;
  console.log(`${name} placeholder: ${placeholder} value: ${value}`);
  return(
    <input placeholder={placeholder} value={value}/>
  );
};

const App = () => {
  const [state,setState] = React.useState('foo');
  
  console.log(`App state: ${state}`);
  
  return(
    <div>
      <SomeInput name={'input1'} placeholder={state}/>
      <SomeInput name={'input2'} value={state}/>
    </div>
  );
};

ReactDOM.render(<App/>,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

Try to log them out and see if they are doing what they are supposed to.

const SomeInput = (props) => {
  const { name, placeholder, value } = props;
  console.log(`${name} placeholder: ${placeholder} value: ${value}`);
  return(
    <input placeholder={placeholder} value={value}/>
  );
};

const App = () => {
  const [state,setState] = React.useState('foo');
  
  console.log(`App state: ${state}`);
  
  return(
    <div>
      <SomeInput name={'input1'} placeholder={state}/>
      <SomeInput name={'input2'} value={state}/>
    </div>
  );
};

ReactDOM.render(<App/>,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文