【问题标题】:How to send an array from child component to parent component in react?如何在反应中将数组从子组件发送到父组件?
【发布时间】:2021-08-24 13:04:37
【问题描述】:

我正在创建一个反应应用程序,我必须将一个数组从子组件发送到父组件。我现在正在尝试使用回调函数发送,但它不起作用。

这是我的子组件:

var apis=[]
export default class ApiDropDown extends React.Component {
  constructor() {
    super();
    this.state = {
      options: [],
      suboptions: [],
    };
  }

  componentDidMount() {
    this.fetchOptions();
  }

  fetchOptions() {
    fetch("http://localhost:5000/groups")
      .then((res) => {
        return res.json();
      })
      .then((json) => {
        this.setState({ options: json });
      });
  }
  //SETTING THE apis here,just adding few elements,its a long function
  onSubmit()
  {
    this.props.apisgranted(apis)
  }


  render() {
  
    return (
      
       
        <div>
          <button type="button" className="btn" onSubmit={this.onSubmit}> //Save button to set data in the prop.
            Save
          </button>
        </div>
      
    );
  }
}

现在这是我的父组件:

const AddTask = ({ onAdd, onStatusChange }) => {
  const [client_name, setText] = useState("");
  const [status, setStatus] = useState("");
  const [showMessage,setMessage]=useState(false)
  const [apigrants,setapigrants]=useState([])

  
 const handleApiGrants = (langValue) => {
    
    setapigrants(langValue) //setting the props array here from child component
    console.log(apigrants)  //nothing gets printed here
}


 

 
  
  return (
    <form className="add-form" onSubmit={onSubmit}>
      <div>
   
      <button onClick={setmessage.bind(false, true)} type="button" className="btn">Grant API's</button>
      
      { showMessage && (<ApiDropDown apisgranted={handleApiGrants} />) } //calling the props handling function where which should set the apigrants array with props array.
      
      </div>

在我的子组件中,我使用onSubmit 函数将数组设置为prop。 在我的父组件中,首先我将 apigrants 数组声明为空,然后使用 handleApiGrants 函数将其分配给子组件的 prop 数组。

【问题讨论】:

  • 您的代码看起来正确。输入像this.props.apisgranted('test data') 这样的值,您将在父组件中看到它。您正在从子组件发送空数组。

标签: javascript html reactjs react-hooks components


【解决方案1】:

最简单的方法是在父组件中定义变量并将其传递给子组件,就像使用 handleApiGrants 一样

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 2017-07-25
    • 2019-04-11
    • 1970-01-01
    • 2021-02-15
    • 2019-08-22
    • 1970-01-01
    • 2020-09-28
    • 2021-05-13
    相关资源
    最近更新 更多