gpt4 book ai didi

javascript - 在使用 Flow 时,如何将 props 传播到使用精确 props 的 React 组件?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:40:59 25 4
gpt4 key购买 nike

考虑以下使用流属性的示例。

import * as React from 'react';

type FooProps = {|
foo: number,
bar?: string
|};

class Foo extends React.Component<FooProps> {}

我们有 React 组件类 Foo接受 Prop 的确切对象。我们希望加强准确性,这样用户就不会无意中在他们的 props 上打错字(例如 baz 而他们本想使用 bar )。

这绝对可以正常工作,并且会按预期发生错误。

但是,如果我们想从其他地方将 props 传播到这个组件怎么办?例如:

const f = (props: FooProps) => <Foo {...props} />;

Flow 会在 props 上给我们一个关于准确性的错误:

10: const f = (props: FooProps) => <Foo {...props} />;
^ Cannot create `Foo` element because inexact props [1] is incompatible with exact `FooProps` [2].
References:
10: const f = (props: FooProps) => <Foo {...props} />;
^ [1]
8: class Foo extends React.Component<FooProps> {}
^ [2]

抛开论点,“当你要求准确性时,你不应该像那样将 props 传播到组件”,如何实现传播?

我确实找到了一种方法来做到这一点,但它使用了一个未记录的实用程序类型 $Shape<T> (code)。目前还不清楚这是否会产生任何后果或副作用,但它似乎可以正常工作:

class Foo extends React.Component<$Shape<FooProps>> {}

这是一个 link to try out what I've got using $Shape<T> 我预计会出错的项目(而不是):

最佳答案

如果这不是来自官方来源,我们深表歉意。

解决方案:将 cast prop 输入到 any传播前。

它满足你在一个函数内传播的要求。该函数确保类型转换之前的准确性。

注意:$Shape<FooProps> Actor 阵容不起作用,它仍然认为它是准确的。也不分配 propsconst spreadable: $Shape<FooProps> = props好像$Shape尽管出现在您的示例中,但不会删除准确性。不管怎样,您必须剥离准确性,并在函数内部执行它似乎是合理的。

The Flow docs discuss type casting via any as legitimate虽然潜在的不安全且不推荐(因为你失去了类型安全)。我认为在上下文中它是合理的。

import * as React from 'react';

type FooProps = {|
foo: number,
bar?: string
|};

class Foo extends React.Component<FooProps> {}

const f = (props: FooProps) => <Foo {...(props: any)} />;

f({foo: 1}) // PASS: with foo, without bar
f({foo: 1, bar: ''}) // PASS: with foo and bar
{ <Foo foo={1} /> } // PASS: with foo, without bar
{ <Foo foo={1} bar="" /> } // PASS: with foo and bar

f({}) // FAIL: missing foo
f({foo: ''}) // FAIL: wrong type of foo
f({foo: 1, bar: 1}) // FAIL: with foo, wrong type of bar
f({foo: 1, x: 1}) // FAIL: unexpected x
{ <Foo /> } // FAIL: missing foo
{ <Foo foo="" /> } // FAIL: wrong type of foo
{ <Foo foo={1} bar={1} /> } // FAIL: with foo, wrong type of bar
{ <Foo foo={1} x={1} /> } // FAIL: unexpected x

Try it here

关于javascript - 在使用 Flow 时,如何将 props 传播到使用精确 props 的 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48842903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com