【问题标题】:ReactJS - How to pass data from child to parent component & parent to child component on the same event?ReactJS - 如何在同一事件上将数据从子组件传递到父组件和父组件到子组件?
【发布时间】:2022-01-18 14:39:35
【问题描述】:

我有一个React 应用程序和组件结构如下所示

app.component.ts

<App>
<Products></Products>
</App>

product.component.ts

export const ProductComponent = () => {

const [category, setcategory] = useState("retail");
const [products, setProducts] = useState([]);   
const categorySelectHandler = (selectedCategory:string) => {
  setcategory(selectedCategory);
}

useEffect(() => {
 getProductsByCategory(category).then((products) => {
  setProducts(products);
   }
  });
  }, [category]);
  
return (
  <>
  <CategorySelector onCategorySelected={categorySelectHandler }></CategorySelector>
  { products.map((product) => {
  return ( 
   <div> 
    <b> {product.name} </b>
    <i> {product.price} </b>
   }
 </>}

categorySelector.component.ts

const CategorySelector: React.FC <CategorySelectorProps> = ({
onCategorySelected,
}) => {

const emptydata: Data[] = [];

const [category, setcategory] = useState("retail");

const [data, setdata] = useState(emptydata);

const categorySelectorHandler = (e: SyntheticEvent) => {
    e.preventDefault();
    const element = e.target as HTMLInputElement;
    setcategory(element.value);
    onCategorySelected(element.value);
};

return ( 
  <div>
    <select defaultValue = {category}  onChange = {categorySelectorHandler} >
     <option value = "retail" > Retail </option> 
     <option value = "electronics" > Electronics < /option> 
  </select>

    {
        data.map((_data: data) => {
            return ( <a href = "#" > {
                    _data.name
                } < /a> <
                /div>
            );
        })
    } 
    </div>
)};

export default CategorySelector;

这里onChange CategorySelector 组件中的下拉事件(子组件)我获取所选值并将其传递给父组件,即ProductComponent。 & 这反过来会触发对 API 的 ajax 调用,该调用将根据所选类别返回产品列表。

到此为止没有问题

现在在同一个事件中,我需要将产品列表传回给子组件,即CategorySelector

长话短说

在子组件中的事件上,将数据传递给父组件(这里没有问题),但是在同一个事件上,我需要将数据从父组件传回子组件组件

【问题讨论】:

  • 为什么需要将类别存储在两个组件的状态中?为什么不把它留在父组件中,作为道具发送给子组件呢?与产品相同。
  • 3 个选项 1) 分解你的组件并有一个产品显示组件并通过道具传递 2) 在父级本身中显示产品 3) 如果你必须合并,那么你必须通过通过现有的categoryselector 产品的道具,并传递categoryselector 选择的选项的值,因为您的categoryselector 现在是一个受控组件,这可能很麻烦。选择 1 个选项
  • 这是我的一个答案,可能有助于提升状态。 stackoverflow.com/questions/70397397/…。这遵循我上面评论中的#1 方法。我认为您的具体示例急需提升状态。
  • @SangeetAgarwal,请您检查并提出建议。谢谢! stackoverflow.com/questions/70851655/…

标签: javascript reactjs


【解决方案1】:

在 API 调用之后,您已经在父组件中设置产品。现在您所要做的就是将产品作为道具传递给子组件。轻轻松松!

<CategorySelector onCategorySelected={categorySelectHandler } products={products}></CategorySelector>

【讨论】:

  • 这种方法的问题是,由于categoryselector 组件被重新渲染,所以选择的选项可能会丢失。请参阅上面的我的 cmets。
  • 是的,我已经尝试过了,但是它确实会重新渲染 CategorySelector 组件
猜你喜欢
  • 2019-01-04
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 2018-04-16
  • 2019-02-27
  • 2017-04-20
相关资源
最近更新 更多