我正在学习React,但不确定如何设置此模式。我只是想念这可能真的很容易。
我有一个控制状态的主要组件。它具有更新状态的所有功能,并通过道具将这些信息向下传递给子组件。我简化了代码,将重点放在这些功能之一上。
现在是组件,所有组件均应正常工作:
ManageMenu.js
import React from 'react'
class ManageMenu extends React.Component {
constructor() {
super()
this.toggleEditing = this.toggleEditing.bind(this)
// Set initial state
this.state = {
menuSections: []
}
}
toggleEditing(id) {
const menuSections = this.state.menuSections
menuSections.map(key => (key.id === id ? key.details.editing = id : ''))
this.setState({ menuSections })
}
render() {
return (
...
)
}
}
export default ManageMenu
toggleEditing通过道具传递给子组件,如果单击了编辑按钮,则该子组件将使用它来呈现编辑表单。
我在此组件中拥有大约10种这些不同的功能,我想做的就是将它们移至外部lib/methods.js
文件,然后引用它们。下面是我想要的代码或类似的代码,但是React不喜欢我在做什么。引发语法错误:
Failed to compile.
Error in ./src/components/ManageMenu.js
Syntax error: Unexpected token
toggleEditing(id, menuSectionId, this.state, this)
这是我想做的...
lib / methods.js
const toggleEditing = function(id, state, that) {
const menuSections = state.menuSections
menuSections.map(key => (key.id === id ? key.details.editing = id : ''))
that.setState({ menuSections })
}
module.exports = {
toggleEditing
}
然后在我的组件中:
ManageMenu.js
import React from 'react'
import { toggleEditing } from '../lib/methods'
class ManageMenu extends React.Component {
constructor() {
super()
// Set initial state
this.state = {
menuSections: []
}
}
toggleEditing(id, this.state, this)
render() {
return (
...
)
}
}
export default ManageMenu
任何帮助表示赞赏,谢谢!
感谢@Nocebo,有关如何将功能外部化的答案在这里:将各种React组件中的通用功能外部化
在我的情况下
toggleEditing(id, this.state, this)
在任何地方删除“浮动”呼叫。更新:发生此错误是“因为它正在调用类定义中的方法。” (请参阅下面的Pineda的评论)this.
右侧的this.toggleEditing
开头constructor()
lib/methods.js
以删除state
和that
变量,因为其绑定到this
中constructor()
请参阅下面的更新代码。
ManageMenu.js
import React from 'react'
import { toggleEditing } from '../lib/methods'
class ManageMenu extends React.Component {
constructor() {
super()
this.toggleEditing = toggleEditing.bind(this)
// Set initial state
this.state = {
menuSections: []
}
}
render() {
return (
...
)
}
}
export default ManageMenu
lib / methods.js
const toggleEditing = function(id) {
const menuSections = this.state.menuSections
menuSections.map(key => (key.id === id ? key.details.editing = id : ''))
this.setState({ menuSections })
}
module.exports = {
toggleEditing
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句