如何在Reactjs组件中将函数作为道具传递?

时间:2019-07-02 11:16:17

标签: reactjs react-props

我需要在一个组件中定义一个函数,然后在同一文件中的另一个组件中调用它。

我不能在同一组件中定义两个函数。此先决条件涉及代码的其他复杂性。

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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>) }

您需要将功能作为道具传递给组件!