【问题标题】:How to pass a function as a prop in reactjs components?如何在 reactjs 组件中将函数作为道具传递?
【发布时间】: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


【解决方案1】:

您确实将函数作为道具传递但没有命名,因此您可以在组件中引用它。 (props)=>{createSVG: (args)=>{func}}

【讨论】:

  • 内部位置标签?我必须在哪里引用它?
  • 你应该在 SchematicEditor 下创建函数,这样你就可以像我向你展示的那样将它作为道具传递给 .PositionLabel 和 Component
【解决方案2】:
const PositionLabel = (props) => {     function createSVG()   {
 alert('yo');   
   }
   return(
   <Component createSVG ={()=>createSVG})
       )
     } 
 const Component = (props) => {       return(   <div
   className='component'>
  <div className="icons">
      <button onClick={()=>props.createSVG}></button>
  </div>   
  </div>) }

您需要将函数作为道具传递给您的组件!

【讨论】:

    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2020-08-28
    • 1970-01-01
    • 2020-10-10
    • 2018-08-09
    相关资源
    最近更新 更多