Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Usando el estado en reaccionar con TypeScript

Soy nuevo en TypeScript. Tengo un problema al mostrar this.state.something dentro del método render o asignarlo a una variable dentro de una función.

Eche un vistazo a la pieza de código más importante:

 interface State { playOrPause?: string; } class Player extends React.Component { constructor() { super(); this.state = { playOrPause: 'Play' }; } render() { return( <div> <button ref={playPause => this.playPause = playPause} title={this.state.playOrPause} // in this line I get an error > Play </button> </div> ); } }

El error dice: "[ts] La propiedad 'playOrPause' no existe en el tipo 'ReadOnly<{}>'.

Intenté declarar la propiedad playOrPause como un tipo de cadena y no funcionó. ¿Qué me estoy perdiendo aquí para que funcione?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Debe declarar que su componente está utilizando la interfaz State, utilizada por Typescript's Generics.

 interface IProps { } interface IState { playOrPause?: string; } class Player extends React.Component<IProps, IState> { // ------------------------------------------^ constructor(props: IProps) { super(props); this.state = { playOrPause: 'Play' }; } render() { return( <div> <button ref={playPause => this.playPause = playPause} title={this.state.playOrPause} // in this line I get an error > Play </button> </div> ); } }
over 4 years ago · Santiago Trujillo Report

0

En caso de que alguien se pregunte cómo implementarlo en componentes funcionales con ganchos (no en una clase) :

 const [value, setValue] = useState<number>(0);

useState es una función genérica, eso significa que puede aceptar un parámetro de tipo. Este parámetro de tipo le dirá a TypeScript qué tipos son aceptables para este estado.

over 4 years ago · Santiago Trujillo Report

0

En mi caso (trabajando con TypeScript, y el valor del estado era en realidad un booleano) tuve el mismo problema, lo arreglé pasando el valor del estado que quería marcar como salida a String():

 import React, { Component } from 'react'; interface ITestProps { name: string; } interface ITestState { toggle: boolean; } class Test extends Component<ITestProps, ITestState> { constructor(props: ITestProps) { super(props); this.state = { toggle: false, }; this.onClick = this.onClick.bind(this); } onClick() { this.setState((previousState, props) => ({ toggle: !previousState.toggle, })); } render() { return ( <div> Hello, {this.props.name}! <br /> Toggle state is: {String(this.state.toggle)} </div> ) } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!