在React 功能组件中,这是设置默认道具,使用Component.defaultProps或使用函数定义上的默认参数的更好方法,示例:
默认道具:
const Component = ({ prop1, prop2 }) => (
<div></div>
)
Component.defaultProps = {
prop1: false,
prop2: 'My Prop',
}
Run Code Online (Sandbox Code Playgroud)
默认参数:
const Component = ({ prop1 = false, prop2 = 'My Prop' }) => (
<div></div>
)
Run Code Online (Sandbox Code Playgroud) 我正在使用React和TypeScript,我已经创建了无状态函数.为了便于阅读,我从示例中删除了无用的代码.
interface CenterBoxProps extends React.Props<CenterBoxProps> {
minHeight?: number;
}
export const CenterBox = (props: CenterBoxProps) => {
const minHeight = props.minHeight || 250;
const style = {
minHeight: minHeight
};
return <div style={style}>Example div</div>;
};
Run Code Online (Sandbox Code Playgroud)
一切都很棒,这段代码工作正常.但有我的问题:我怎么可以定义defaultProps为CenterBox组件?
正如反应文档中提到的那样:
(...)它们是输入的纯函数变换,没有样板.但是,您仍然可以通过将它们设置为函数的属性来指定.propTypes和 .defaultProps,就像在ES6类上设置它们一样.(......)
它应该很容易:
CenterBox.defaultProps = {
minHeight: 250
}
Run Code Online (Sandbox Code Playgroud)
但是此代码生成TSLint错误: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.
再说一遍:我怎样才能defaultProps在上面的堆栈中正确定义(React + TypeScript)?
我有一个 SFC React 组件,其 Flow 运行如下:
// @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;
Run Code Online (Sandbox Code Playgroud)
我从 Flow 中收到以下错误:
Cannot coerce 'props.placeholderText' to string because undefined[1] should not be coerced (References: [1])
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下这是怎么回事以及修复方法是什么吗?
据我所知,我已经明确告诉 Flow 是placeholderText一个字符串,而且,由于它不是必需的 prop,我已将默认 prop 设置为空字符串,因此它永远不会为 null 或未定义。