Javascript 模板文字中的prop字符串的流错误
我有一个SFC React组件,其流程如下:Javascript 模板文字中的prop字符串的流错误,javascript,reactjs,flowtype,Javascript,Reactjs,Flowtype,我有一个SFC React组件,其流程如下: // @flow import React from 'react'; type Props = { placeholderText?: string, }; const defaultProps = { placeholderText: '', }; const Textarea = (props: Props) => ( <textarea placeholder={`${props.placeholderText
// @flow
import React from 'react';
type Props = {
placeholderText?: string,
};
const defaultProps = {
placeholderText: '',
};
const Textarea = (props: Props) => (
<textarea placeholder={`${props.placeholderText}`} />
);
Textarea.defaultProps = defaultProps;
export default Textarea;
有人能解释一下这是怎么回事吗?解决办法是什么
据我所知,我已经明确告诉Flow,占位符文本是一个字符串,而且,由于它不是必需的属性,我已经将默认属性设置为空字符串,因此它从不为null或未定义。根据,您的属性类型可以被视为组件的“内部”类型。如果希望Props
成为组件API的文档,可以在函数中使用默认值:
type Props = {
placeholderText?: string,
};
const Textarea = (props: Props) => {
const { placeholderText = '' } = props;
return <textarea placeholder={`${placeholderText}`} />
};
类型道具={
占位符文本?:字符串,
};
常量文本区域=(道具:道具)=>{
const{placeholder text=''}=props;
返回
};
我不确定您是否已结账:
似乎很多人都在谈论这个问题。不幸的是,我真的不认为任何建议的方法是特别伟大的
第一个是证监会特有的,你可以这样做
const Textarea = ({placeholderText = ""}: Props) => (
<textarea placeholder={`${placeholderText}`} />
);
consttextarea=({placeholder text=”“}:Props)=>(
);
^在这里,当我们从道具中解构占位符文本时,我们设置了一个默认值。这对于你的例子来说是可行的,但对于其他更复杂的情况,这并不理想
另一个选项也不理想:要从占位符文本中删除可选类型以有效地绕过错误,请执行以下操作:
import React from 'react';
type Props = {
placeholderText: string, // here's the change
};
const defaultProps = {
placeholderText: '',
};
const Textarea = (props: Props) => (
<textarea placeholder={`${props.placeholderText}`} />
);
Textarea.defaultProps = defaultProps;
export default Textarea;
从“React”导入React;
类型道具={
占位符文本:string,//这是更改
};
const defaultProps={
占位符文本:“”,
};
常量文本区域=(道具:道具)=>(
);
Textarea.defaultProps=defaultProps;
导出默认文本区域;
关于设置SFC defaultProps,这可能是同一个问题,也许可以试着看一下:@K.F谢谢你的帮助,但我在这方面没有取得任何进展,部分原因是因为这与Typescript有关,但也有一些事情我尝试过,但没有帮助。谢谢你的帮助,但这项技术没有通过Airbnb eslint规则(道具不是必需的,但没有相应的defaultProp)React docs不是指定如何应用默认值的方式吗。@Coop这很不幸。你说得对,defaultProps
是设置默认道具的更好方式,但是现在似乎没有办法在类型中同时使用可选道具和在Flow中使用defaultProps
。谢谢你的帮助。Flow不能这样做,我感到非常震惊处理这个问题,这似乎是一个基本的要求。谢谢你的建议。Flow不能正确处理这个简单的事情,这真是一个大开眼界。这让我想知道Typescript是否能做得更好。你的第一个选项,虽然不是理想的设置({Placeholder Text=defaultProps.Placeholder Text}:Props)
import React from 'react';
type Props = {
placeholderText: string, // here's the change
};
const defaultProps = {
placeholderText: '',
};
const Textarea = (props: Props) => (
<textarea placeholder={`${props.placeholderText}`} />
);
Textarea.defaultProps = defaultProps;
export default Textarea;