【问题标题】:How to use a javascript function from a React js component如何使用 React js 组件中的 javascript 函数
【发布时间】:2019-05-05 06:36:52
【问题描述】:

我有 index.js,这是一个没有类的 javascript 文件,它使用 RenderDOM 来渲染组件时间线并使用数据初始化一些数组,并且 index.js 有一个函数 playSound(),我已将 playSound 作为道具发送到时间线,但它返回错误 this.props.playSound is not a function。

对于不同的函数名称,即“playSound()”,它可以工作,但对于“onPlayFrames”,它不会在timeline.jsx 上被识别为函数

我这样发送道具:(index.js)

function onPlayFrames(arg){
    // Code to play a sound with arg
}

ReactDOM.render(
    <Timeline onPlayFrames={onPlayFrames}/>
    ,document.getElementById("root")
)

并像这样在时间轴上使用它:(timeline.jsx)

class Timeline extends React.Component {
  constructor(props) {
          super(props);
      }

  playStop(arg) {
      this.props.onPlayFrames(arg);
  }
}

当我尝试使用该功能时,我只是收到错误“this.state.onPlayFrames is not a function”,我做什么并不重要

【问题讨论】:

    标签: javascript reactjs function


    【解决方案1】:

    我刚试过这个代码笔。这是你的要求吗?

    function playSound(){
      alert("faf");// Code to play a sound with arg
    }
    class Test extends React.Component{
    render(){
      return <button onClick={()=>this.props.play()}>faf</button>
    }
    }
    const Parent = ()=> <Test play={playSound}/>;
    
    ReactDOM.render(
      <h1><Parent/></h1>,
      document.getElementById('root')
    );
    

    【讨论】:

      【解决方案2】:

      在timeline.jsx中:

      playStop(arg) {
        this.props.onPlayFrames(arg);
      }
      

      这应该是this.props.playSound(arg)。原因是它必须与您用作属性的内容相匹配 na:

      <Timeline playSound={playSound}/>
      

      为了更清楚,想象一下你是这样做的:

      ReactDOM.render(
          <Timeline foobar={onPlayFrames}/>
          ,document.getElementById("root")
      )
      

      时间轴上的属性现在是foobar,这意味着在时间轴上,它将通过名为foobar 的属性传递给 onPlayFrames 函数。

      class Timeline extends React.Component {
        constructor(props) {
                super(props);
            }
      
        playStop(arg) {
            this.props.foobar(arg);
        }
      }
      

      【讨论】:

      • 谢谢,我写错了代码,但是,当我尝试使用名称“onPlayFrames”时,它不起作用,使用“playSound”,它可以完美运行,知道为什么吗?
      • 我已经更新了答案,以帮助解释它为什么起作用以及关系是什么,因为道具名称是什么
      猜你喜欢
      • 2018-07-05
      • 1970-01-01
      • 2023-01-10
      • 2019-05-04
      • 2019-05-20
      • 2014-01-30
      • 2020-10-24
      • 1970-01-01
      • 2022-10-20
      相关资源
      最近更新 更多