如何在父组件中使用子组件的状态?

时间:2020-01-13 04:46:24

标签: javascript reactjs

我需要使用父组件中子组件内部的状态值。

组件:

export default function Children(props) {

    const [data,setData] = useState('')

     const handleChange = (e) =>{
        e.preventDefault();
        setData({[e.target.name]:e.target.value});

     }
    return(
        <Component onChange={handleChange} name={props.name} label={props.name} variant="outlined" />
    );
};

这是父组件:

export default function Parent(){

    return(
        <div>
        <TextArea name="One"/>
        <TextArea name="Two"/>
        <TextArea name="Three"/>
        </div>
);}

2 个答案:

答案 0 :(得分:3)

您只能在父组件中拥有stateonChange处理程序。

export default function Splitter(){
    const [data,setData] = useState('')

    const handleChange = (name, value) =>{
        setData({[name]:value});
     }
    return(
        <div>
        <TextArea name="Nome" handleChange={handleChange}/> //Pass the change handler here
        <TextArea name="Test" handleChange={handleChange}/>
        <TextArea name="Local" handleChange={handleChange}/>
        </div>
);}

在子组件中,从父组件中调用函数,

export default function TextArea(props) {

     const handleChange = (e) =>{
        props.handleChange(e.target.name, e.target.value)
     }

    return(
        <CssTextArea onChange={handleChange} name={props.name} label={props.name} variant="outlined" />
    );
};

答案 1 :(得分:0)

您在找这样的东西吗?

import React from "react";
import "./styles.css";

const Comp1 = () => <h2>Component One</h2>;
const Comp2 = () => <h2>Component Two</h2>;
const Comp3 = () => <h2>Component Three</h2>;

export default function TextArea(props) {
  const [data, setData] = React.useState("");

  const handleChange = e => {
    e.preventDefault();
    setData(e.target.value);
  };
  console.log(data);
  return (
    <>
      <h3>Please select to show Component</h3>
      <CssTextArea
        onChange={handleChange}
        name={props.name}
        label={props.name}
        variant="outlined"
      />
      {data === "One" && <Comp1 />}
      {data === "Two" && <Comp2 />}
      {data === "Three" && <Comp3 />}
    </>
  );
}
const CssTextArea = ({ onChange }) => {
  let arr = ["One", "Two", "Three"];
  return (
    <select onChange={onChange}>
      <option value="">Select</option>
      {arr.map(a => (
        <option value={a} key={a}>
          {a}
        </option>
      ))}
    </select>
  );
};

实时Demo