Could anyone show an example of defining defaultProps
on a React component class in TypeScript?
interface IProps {} interface IState {} class SomeComponent extends Component<IProps, IState> { // ... defaultProps ? // public defaultProps: IProps = {}; // This statement produces an error constructor(props: IProps) { super(props); } // ... }
To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.
You can define default props this way: export class Counter extends React. Component { constructor(props) { super(props); this. state = {count: props.
You can define default props this way:
export class Counter extends React.Component { constructor(props) { super(props); this.state = {count: props.initialCount}; this.tick = this.tick.bind(this); } tick() { this.setState({count: this.state.count + 1}); } render() { return ( <div onClick={this.tick}> Clicks: {this.state.count} </div> ); } } Counter.propTypes = { initialCount: React.PropTypes.number }; Counter.defaultProps = { initialCount: 0 };
This is equivalent in TypeScript to defining defaultProps as a static field inside the class body:
class SomeComponent extends Component<IProps, IStates> { public static defaultProps: IProps = { /* ... */ }; // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With