我正在尝试使用React.forwardRef,但是如何让它在基于类的组件(而不是HOC)中工作.
docs示例使用元素和功能组件,甚至在高阶组件的函数中包装类.
所以,从他们的ref.js文件中的这样的东西开始:
const TextInput = React.forwardRef(
(props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />)
);
Run Code Online (Sandbox Code Playgroud)
而是将其定义为:
class TextInput extends React.Component {
render() {
let { props, ref } = React.forwardRef((props, ref) => ({ props, ref }));
return <input type="text" placeholder="Hello World" ref={ref} />;
}
}
Run Code Online (Sandbox Code Playgroud)
要么
class TextInput extends React.Component {
render() {
return (
React.forwardRef((props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />))
);
}
}
Run Code Online (Sandbox Code Playgroud)
只有工作:/
另外,我知道我知道,参考不是反应方式.我正在尝试使用第三方画布库,并希望在单独的组件中添加一些工具,因此我需要事件监听器,因此我需要生命周期方法.以后它可能会走另一条路,但我想尝试一下.
文档说这是可能的!
Ref转发不仅限于DOM组件.您也可以将refs转发给类组件实例.
但后来他们继续使用HOC而不仅仅是课程.
看看 graphene_django,我发现他们有一堆解析器拾取 django 模型字段,将它们映射到石墨烯类型。
我有一个JSONField的子类,我也希望被选中。
:
# models
class Recipe(models.Model):
name = models.CharField(max_length=100)
instructions = models.TextField()
ingredients = models.ManyToManyField(
Ingredient, related_name='recipes'
)
custom_field = JSONFieldSubclass(....)
# schema
class RecipeType(DjangoObjectType):
class Meta:
model = Recipe
custom_field = ???
Run Code Online (Sandbox Code Playgroud)
我知道我可以为查询编写一个单独的字段和解析器对,但我更希望将其作为该模型架构的一部分。
我意识到我可以做什么:
class RecipeQuery:
custom_field = graphene.JSONString(id=graphene.ID(required=True))
def resolve_custom_field(self, info, **kwargs):
id = kwargs.get('id')
instance = get_item_by_id(id)
return instance.custom_field.to_json()
Run Code Online (Sandbox Code Playgroud)
但是——这意味着一个单独的往返,获取 id,然后获取该项目的 custom_field,对吧?
有没有办法将其视为 RecipeType 架构的一部分?