【发布时间】:2019-11-13 00:42:42
【问题描述】:
我需要在一个组件中定义一个函数并在另一个组件中调用它,两者都在同一个文件中。
我不能在同一个组件中定义这两个函数。此先决条件涉及代码的其他复杂性。
const SchematicEditor = () => {
return(
<div>
<Component />
<ReactCursorPosition className="editor"
activationInteractionMouse={INTERACTIONS.CLICK}>
<PositionLabel />
</ReactCursorPosition>
</div>
)
}
const PositionLabel = (props) => {
function createSVG()
{
alert(width);
}
const {
elementDimensions: {
width = 0,
height = 0
} = {},
isActive = false,
isPositionOutside = false,
position: {
x = 0,
y = 0
} = {}
} = props;
return (
<div className="window" id = "canvas">
{x: ${x}}<br />
{y: ${y}}<br />
{width:: ${width}}<br />
{height: ${height}}<br />
{isActive: ${isActive}}<br />
{isPositionOutside: ${isPositionOutside ? 'true' : 'false'}}<br />
</div>
);
};
const Component = (props) => {
return(
<div className='component'>
<div className="icons">
<button onClick={() => props.createSVG()}><a href = "" id = "vsource" className="btn-floating btn-large waves-effect waves-light white"><i className="material-icons"><img src={vsource} alt={'v source'}/></i></a></button>
</div>
</div>
)
}
export default SchematicEditor;
我收到错误Function not defined。
【问题讨论】:
-
PositionLabel 应该返回一些 jsx? createSVG() 是 PositionLabel 的一部分。请添加将道具传递给“组件”组件的代码。
-
@SebinBenjamin 我已经编辑并包含了完整的代码
-
快速说明:无状态功能组件不能有方法。您可以在组件函数之外声明函数并重用相同的引用。当你在里面声明函数时,每次渲染组件时都会不必要地重新定义函数。阅读stackoverflow.com/questions/46138145/…中的答案
标签: reactjs react-props