我正在尝试使用一个函数,该函数与App.js
位于不同的组件中。
而且我遇到语法错误,我不知道我做错了什么。我在App.js
中有一个按钮,当我单击它时,应该触发前面提到的另一个组件中的功能。
app.js :
import React from 'react';
import {shaking} from './components/Tree/Tree.js';
class App extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
shaking();
console.log("done !");
}
render() {
return (
<div>
<Tree className='tree' />
<Apples />
<Basket />
<br/>
<button className="start-btn" onClick={this.handleClick}>Start !</button>
<br/>
</div>
);
}
};
export default App;
这是我的另一个组件:
import React from 'react';
import TreeSvg from './Tree-svg/TreeSvg.js';
import './Tree.sass';
export function shaking(){
const tree = document.getElemenetsByClassName(".tree-img")[0];
tree.classList.add("apply-shake");
console.log('shaked!');
}
class Tree extends React.Component{
constructor() {
super();
this.shaking = this.shaking.bind(this);
}
shaking() {
this.setState({shaked:'1'});
const tree = document.getElemenetByClassName(".tree-img");
tree.classList.add("apply-shake");
console.log('shaked!');
}
render(){
return(
<div className="tree-img">
<TreeSvg />
</div>
);
}
};
export default Tree;
答案 0 :(得分:0)
使您的Tree组件像这样
import React from 'react';
import TreeSvg from './Tree-svg/TreeSvg.js';
import './Tree.sass';
export function shaking(){
const tree = document.getElementsByClassName(".tree-img")[0];
tree.classList.add("apply-shake");
console.log('shaked!');
}
class Tree extends React.Component{
constructor() {
super();
this.state = {
shaked : ''
}
shaking() {
this.setState({shaked:'1'});
const tree = document.getElementByClassName(".tree-img");
tree.classList.add("apply-shake");
console.log('shaked!');
}
render(){
return(
<div className="tree-img">
<TreeSvg />
</div>
);
}
};
export default Tree;
答案 1 :(得分:0)
您的代码中确实有2个语法错误。两者都位于Tree
组件文件中。
const tree = document.getElemenetsByClassName(".tree-img")[0];
将Elemenets
替换为Elements
。shaking()
中(第21行):
const tree = document.getElemenetByClassName(".tree-img");
用Elemenet
替换Element