gpt4 book ai didi

javascript - 在 React 类中声明并重用变量?

转载 作者:行者123 更新时间:2023-12-01 02:07:54 25 4
gpt4 key购买 nike

使用 React 中的纯函数,可以轻松地使您创建的任何变量都可以被任何其他嵌套函数重用:

const myComponent = props => {
const {something} = props.nested;

const nestedFunction = () => {
if (something === "value") return true
}

const otherNestedFunction = () => {
console.log(otherNestedFunction)
}

return (
// markup
)
}

你能用 React 类做类似的事情吗?目前我必须重复创建变量。

class myComponent extends React.Component() {

nestedFunction() {
const {something} = props.nested;
if (something === "value") return true
}

otherNestedFunction() {
const {something} = props.nested;
console.log(otherNestedFunction)
}

render(){
return (
// markup
)
}
}

最佳答案

要在 ES6 类的函数之间共享变量,请使用成员变量。 React 提供 props 作为成员变量,您可以使用 this.props 访问它:

class myComponent extends React.Component() {

nestedFunction() {
if (this.props.nested === "value") return true
}

otherNestedFunction() {
console.log(this.props.nested)
}

render(){
return (
// markup
)
}
}

请注意,您永远不应该分配或以其他方式改变任何 Prop 的值。相反,使用状态和 this.setState() 来更新内部组件状态并触发生命周期事件来更新子组件。

关于javascript - 在 React 类中声明并重用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49952265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com