【问题标题】:I want to pass data to parent component foom a child component using props我想使用 props 将数据传递给父组件 foom 子组件
【发布时间】:2023-01-27 16:53:04
【问题描述】:

我正在尝试使用子组件 TagsInput.js 中的道具将数据传递给父组件 Top.js,我可以在其中添加标签但是 我不明白是什么导致了错误......

我想要达到的目标

我想将“标签”从带有道具的子组件中的 TagsInput.js 传递给父组件 Top.js。

我得到了这样的错误

props.setTagsinput is not a function

标签输入.js

import React from "react";

const TagsInput = (props) => {

    //1, Define the tags variable to store the entered tags. (I want to pass the value of the tags variable to the parent component Top.js)
    const [tags, setTags] = React.useState([]);

    //2, Put formText in the function received from the parent component and return it.
    props.setTagsinput(tags);
    console.log(props)

    let tag_list = []
    tag_list.push(tags);


    const addTags = event => {
      if (event.key === "Enter" && event.target.value !== "") {
          setTags([...tags, event.target.value]);
          event.target.value = "";
      }
    };
    const removeTags = index => {
      setTags([...tags.filter(tag => tags.indexOf(tag) !== index)]);
    };

    return (
        <div className="tags-input">
            <div className="tags_section">
                {tags.map((tag, index) => (
                    <div className="tag tag-flex" key={index}>
                            <p className="tag-p">{tag}</p>
                    </div>
                ))}
            </div>
            <input
                type="text"
                onKeyUp={event => addTags(event)}
                placeholder="Press enter to add tags"
            />
        </div>
    );
};
export default TagsInput;

Top.js

import React, {useState, useEffect} from 'react';
import axios from 'axios';
import Student from './Student';
import TagsInput from "./TagsInput";

const Top = () => {
  const [ posts, setPosts] = useState([]);
  const [ allPosts, setAllPosts] = useState([]);

  let tag_list = []
  const [searchKeyword, setSearchKeyword] = React.useState("");
  const [searchTagKeyword, setTagSearchKeyword] = React.useState("");
  console.log(searchKeyword)


  const[tags_from_tagsinput, setTagsinput]= useState("");
  console.log(tags_from_tagsinput);

  useEffect(() => {
    axios.get('xxx.com')
    .then(result => {
      setPosts(result.data.students);
      setAllPosts(result.data.students);
      if (searchKeyword) {
        getSearchResult()
      }
    })},
    [searchKeyword]);



  const getSearchResult = () => {
    console.log(searchKeyword)
    const result = allPosts.filter((output, index) => {
      return output.firstName.toLowerCase().includes(searchKeyword.toLowerCase())||output.lastName.toLowerCase().includes(searchKeyword.toLowerCase());
    });
    console.log(result)
    setPosts(result);
  };


  
  const getTagSearchResult = () => {
    console.log(searchTagKeyword)
    const result = allPosts.filter((output, index) => {
      return output.lastName.toLowerCase().includes(searchTagKeyword.toLowerCase());
    });
    console.log(result)
    setPosts(result);
  };

  return (
    <div>
      <TagsInput setTagsinput={setTagsinput}/>
      <div>
      <input className="search-box" placeholder="" value={searchKeyword} onChange={(e) => setSearchKeyword(e.target.value)}/>
      </div>
      <div>
      <input className="search-box" placeholder="" value={searchTagKeyword} onChange={(e) => setSearchKeyword(e.target.value)}/>
      </div>
      <div>
      {searchKeyword &&
      <p>{searchKeyword} Search</p>
      }
      {posts ?
      <>
        {posts.map((data, i) =>
          <Student data={data} />
        )}
      </>
      :
      <div>
        <p>Not Found!</p>
      </div>
      }
      </div>
    </div>
  );
}
export default Top;

学生.js

import React, {useState} from 'react';
import TagsInput from './TagsInput';

const Student = (props) => {
const [show, setShow] = useState(false)

  const gradesAverage = (grades) => {
    let sum = 0;
    grades.forEach(function(score) {
      sum += Number(score);
    });
    let ave = sum / grades.length
    return ave;
  };

  return (
    <div className="flex">
        <div className="image">
            <img src={props.data.pic} className="profile" />
        </div>
        <div>
            <p className="name">{props.data.firstName} {props.data.lastName}</p>
            <button className="button" onClick={() => setShow(!show)}>
                {show? <div className="button_p">-</div>:<div className="button_p">+</div>}
            </button>
            <div className="info">
                <p>Email: {props.data.email}</p>
                <p>Company: {props.data.company}</p>
                <p>Skill: {props.data.skill}</p>
                <p>Average Grade: {gradesAverage(props.data.grades)}%</p>
                {show &&
                    <>
                        <p>Test 1: {props.data.grades[0]}%</p>
                        <p>Test 2: {props.data.grades[1]}%</p>
                        <p>Test 3: {props.data.grades[2]}%</p>
                        <p>Test 4: {props.data.grades[3]}%</p>
                        <p>Test 5: {props.data.grades[4]}%</p>
                        <p>Test 6: {props.data.grades[5]}%</p>
                        <p>Test 7: {props.data.grades[6]}%</p>
                        <p>Test 8: {props.data.grades[7]}%</p>
                    </>
                }
                <TagsInput />
            </div>
        </div>
    </div>
  );
}
export default Student;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    在你的顶部component你可以创建一个函数来更新你的tags_from_tagsinput钩子然后将props传递给孩子component

    import TagsInput from "./TagsInput";
    const Top = () => {
    
      const[tags_from_tagsinput, setTagsinput]= useState("");
      console.log(tags_from_tagsinput);
    
      const getTag = (value) => {
        setTagsinput(value);
      };
    
    
      return (
        <div>
          <TagsInput  getTag={getTag} />
        </div>
      );
    }
    export default Top;
    

    现在从你的 TagsInput component 你可以调用这个函数来更新 Top 的 tags_from_tagsinput,假设你想在用户点击按钮时更新

    import React from "react";
    
    const TagsInput = (props) => {
    
        return (
            <div className="tags-input">
             ...
            <button onClick={()=>{props.getTag(tags)}}>updated parent component</button>
            </div>
        );
    };
    export default TagsInput;
    

    【讨论】:

    • 抱歉,信息较少。实际上 TagsInput 是在 Student.js 中使用的(我添加的),而不是 Top.js。那么如何将“标签”传递给 Top.js?
    • 您将此函数从 Top 传递给学生 &lt;Student getTag={getTag} /&gt;,然后从学生传递给 TagsInput &lt;TagsInput getTag={props.getTag} /&gt;,就像上面的示例一样,您可以从 TagInput 使用它
    猜你喜欢
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多