【问题标题】:How to get params and type definition for custom React/React-Native components如何获取自定义 React/React-Native 组件的参数和类型定义
【发布时间】:2021-08-17 02:03:30
【问题描述】:

我构建了一个自定义的 React Native 输入组件,它在聚焦时在底部显示一个黑色边框,但是当我使用这个组件时,我没有得到 VS Code Intellisense 提供的道具建议。

function TextInputComponent(props) {
  const [controlledValue, setControlledValue] = useState('');
  const [focused, setFocused] = useState(false);
  const {
    placeholder,
    onChangeText,
    autoCapitalize,
    ref,
    secureTextEntry,
    value,
    defaultValue,
    controlled,
    editable,
    ...rest
  } = props;
  return (
    <TextInput
      ref={ref}
      value={controlled ? controlledValue : value}
      defaultValue={defaultValue}
      secureTextEntry={secureTextEntry}
      placeholder={placeholder}
      placeholderTextColor={globalColors.semiGray}
      autoCapitalize={autoCapitalize}
      editable={editable}
      mode="outlined"
      onFocus={() => {
        setFocused(true);
      }}
      onBlur={() => {
        setFocused(false);
      }}
      style={[
        styles.textInput,
        focused ? {borderColor: globalColors.blue} : {},
      ]}
      onChangeText={text => {
        if (controlled) {
          console.log(text.toLowerCase());
          setControlledValue(text.toLowerCase());
          onChangeText(text);
        } else {
          onChangeText(text);
        }
      }}
      {...rest}
    />
  );
}

const styles = StyleSheet.create({
  textInput: {
    ...elementStyles.input,
  },
});

有什么方法可以在不使用 TypeScript 的情况下获取 prop 和类型定义?

/**
 * 
 * @param {{header: string, subheader: string, imageAlt: string, contentList: Array, orderLink: Object, contentLink: Object}} props 
 */

我已经看到了@params 的定义方式,但我只想扩展默认的 TextInput 定义,而不是为我的自定义组件再次编写所有类型定义。

【问题讨论】:

  • 我使用类型定义道具。简单地定义一个类型,例如:type props = { name: string; value?: number } 并将其传递给功能组件 const Bar: React.FC&lt;props&gt; = (props) =&gt; { ... code ... return &lt;&gt;{... return code ...}&lt;/&gt; } 的箭头函数,这样就可以确定必须添加哪些变量以及哪些变量可以是有条件的(使用?)。 IMO - 简单、快速和 ez。最好的 aprt - 类型可以被其他组件或变量导出和使用,甚至可以扩展,以便组件可以继承该类型并向其添加更多内容。

标签: reactjs typescript react-native visual-studio-code


【解决方案1】:

检查Prop-Types 。你可以很容易地用它做道具检查

【讨论】:

猜你喜欢
  • 2022-11-24
  • 2016-09-25
  • 2017-12-30
  • 2022-06-11
  • 2018-11-16
  • 2021-01-15
  • 2018-02-09
  • 2016-01-26
  • 1970-01-01
相关资源
最近更新 更多