reactjs - React 构造函数中的 : Setting this. 属性...? (不试图改变 Prop )

标签 reactjs ecmascript-6

我并不想改变 Prop 。 我只想在构造函数中调用的方法中访问 this.props:

constructor(props){
    super(props);

    this.props = props; // CAN I? There is no errors or warnings

    const filtered = this.filterValue(props.value);
    this.state = {
        value: filtered,
    }
}

filterValue(value){
    // here I need this.props.*
}

我知道有几种方法可以做到这一点,例如传递给 filterValue 的附加参数,但我希望它尽可能简单。我认为上面的代码是 很直观,问题是:我可以这样做吗?无论如何,React 都会覆盖 this.props。

最佳答案

您可以在方法中使用 this.props 访问 Prop ,如 the React.Component documentation 中所述。 :

Instance Properties:

  • props

  • state

如果你好奇的话,可以看一下ReactComponent constructor的源代码.

关于reactjs - React 构造函数中的 : Setting this. 属性...? (不试图改变 Prop ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38567086/

相关文章:

reactjs - "To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."错误但我没有使用它

javascript - 在 ReactJS 中,我的代码是否有支持实例,因此可以使用引用?

node.js - 如何使用 babel 构建非 js 文件?

javascript - 如何编写名为 `add` 的单个函数。这样一旦它收到 2 个参数,它就会返回 2 个值的总和

javascript - react 路由器 v4 onUpdate

javascript - ReactJS加载函数 “is not a function”

reactjs - 我的数据测试 ID 在那里,但我的测试找不到它 react enzyme Jest 单元测试

javascript - 去抖动

javascript - ReactJS 在无效页面上隐藏标题 (404)

javascript - 如何从数组中排除某些键