简体   繁体   English

如何使用React JS组件中的javascript函数

[英]How to use a javascript function from a React js component

I have index.js, that is a javascript file with no classes which uses RenderDOM to render the component timeline and initialize some arrays with data, and index.js have a function playSound(), I have sent playSound as a prop to timeline, but it returns error this.props.playSound is not a function. 我有index.js,这是一个没有类的javascript文件,它使用RenderDOM渲染组件时间轴并使用数据初始化一些数组,而index.js具有功能playSound(),我已将playSound发送为时间轴的道具,但它返回错误this.props.playSound不是函数。

For a different function name ie "playSound()" it works, but with"onPlayFrames" it don't get recognized as function on timeline.jsx 对于不同的函数名称(例如“ playSound()”),它可以工作,但在“ onPlayFrames”中,它不会在timeline.jsx上被识别为函数

I send the prop like this: (index.js) 我发送的道具是这样的:(index.js)

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

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

and use it on timeline like this: (timeline.jsx) 并在时间轴上使用它,如下所示:(timeline.jsx)

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

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

i just get the error "this.state.onPlayFrames is not a function" when i try to use the function, it doesn't matters what i do 当我尝试使用该函数时,我只是收到错误“ this.state.onPlayFrames不是一个函数”,这与我做什么无关紧要

Within timeline.jsx: 在timeline.jsx中:

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

This should this.props.playSound(arg) . 这应该是this.props.playSound(arg) The reason is because it has to match what you are using as a property na: 原因是因为它必须匹配您用作属性na的内容:

<Timeline playSound={playSound}/>

To make it clearer, imagine you did this: 为了更清楚地说明,假设您这样做:

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

The Property on Timeline is now foobar which means on Timeline, it will be passed the onPlayFrames function via a property called foobar . 现在,时间轴上的属性为foobar ,这意味着在时间轴上,它将通过名为foobar的属性传递给onPlayFrames函数。

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

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

I just tried this code pen.Is this what your asking? 我刚试过这支密码笔,这是您的要求吗?

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')
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM