【问题标题】:React Js component constructor and visible stateReact Js 组件构造函数和可见状态
【发布时间】:2020-10-02 11:52:48
【问题描述】:

我想要做的是启动该反应组件为不可见。所以我尝试做一个构造函数,但在构造函数中我得到:

';'预计

和:

'this' 隐含类型 'any' 因为它没有类型 annotation.ts(2683) Registro.tsx(40, 10): 'this' 的外部值为 被这个容器遮蔽。 'this' 隐含类型为 'any' 因为 它没有类型 annotation.ts(2683) Registro.tsx(40, 10): An 'this' 的外部值被此容器遮蔽。 'this' 含蓄地 具有类型“任何”,因为它没有类型 annotation.ts(2683) Registro.tsx(40, 10): 'this' 的外部值被 this 遮蔽 容器。

const RegistroNuevaCuenta: React.FC = ( ) => {

  constructor() {
  
    this.state = {
      childVisible: false
    };
  }

  const [text, setText] = useState<string>();
  const [number, setNumber] = useState<number>();

  return (
    <div className="contenedor_central">
      <strong>Completá tus datos</strong>
      
      <IonItem>
        <IonLabel position="floating">Nombre</IonLabel>
        <IonInput value={text}></IonInput>
      </IonItem>
      <IonItem>
        <IonLabel position="floating">Apellido</IonLabel>
        <IonInput value={text}></IonInput>
      </IonItem>
      <IonItem>
        <IonLabel position="floating">E-mail</IonLabel>
        <IonInput value={text}></IonInput>
      </IonItem>
      <IonItem>
        <IonLabel position="floating">Clave</IonLabel>
        <IonInput value={text}></IonInput>
      </IonItem>

    </div>
  );
};

如何在 Jsx 中设置构造函数? 提前致谢。

【问题讨论】:

  • 构造函数仅用于基于类的组件。看起来您正在使用功能组件
  • 有两种类型的组件 - 类和函数式 - 在 reactjs docs 上阅读它们。
  • 我把它改成一个类但它没有隐藏:class MouseTracker extends React.Component { constructor(props: Readonly) { super(props); this.state = { isHidden: false, }; }

标签: javascript reactjs


【解决方案1】:

我不完全确定您要做什么,但您不能混合使用类和函数。

使用构造函数意味着你在一个类中,在它之外你不能。

我想要设置另一个状态值,就像你为文本和数字所做的那样。然后你可以做类似的事情

if (isHidden) return null;

但是你必须处理你的组件如何变得可见。

【讨论】:

    【解决方案2】:

    需要在useState调用中直接设置默认状态: https://reactjs.org/docs/hooks-state.html#declaring-a-state-variable

    const [childVisisble, setChildVisible] = useState(false);

    您正在尝试在无法完成的功能组件中使用构造函数: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2017-07-14
      相关资源
      最近更新 更多