在构造函数调用之前如何修改道具?

时间:2019-02-14 23:20:04

标签: reactjs react-native

我想在调用构造函数之前将对象的类作为prop传递,然后实例化它。

export class Knight implements AbstractCharacter {
  public name = "Knight";
  public hp = 500;
  public damage = 1000;
}

反应成分:

export default class CharacterView extends React.Component {
    constructor(props) {
      super(props);
      this.props.character = new props.character() // this isn't allowed
     }
    render() {
       return(
            <Text>
                  HP: {"" + this.props.character.hp}, Dmg: {this.props.character.damage}
            </Text>
     }

致电:

 <CharacterView character = {Knight} />   // won't work
 <CharacterView character = {new Knight()} /> // Would work, but it doesn't follow DRY principle. Also I would want to have multiple instances of Knight()

要在python中执行此操作,我将使用__new__构造函数,而不是__init__。 JS中是否有类似的东西,您可以在其中拦截构造函数?

0 个答案:

没有答案