以下是我的代码:
import React, { Component } from 'react';
import './App.css';
class buttonGroup extends Component{
render(){
return (<button onClick={this.countClick}>Count it up</button>);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
message:"state from constructor",
counter: 1
};
this.handleClick = this.handleClick.bind(this);
this.countClick = this.countClick.bind(this);
}
handleClick(e) {
this.setState( () => ({message:"state from click handler"}) )
}
countClick(e) {
this.setState( (prev, props) => ({counter: (prev.counter + 1)}))
}
render() {
return (
<div>
<div>
<h1>{this.state.message}</h1>
<h1>{this.state.counter}</h1>
</div>
<button onClick={this.handleClick}>Change it up</button>
<buttonGroup/>
</div>
);
}
}
export default App;
我知道这可能是明显的东西,但我似乎无法在“buttonGroup”中获得“计数”按钮来渲染。我已经尝试添加括号,将它们带走,重新排序所有内容。
请帮助我。
答案 0 :(得分:1)
你必须写得像:
<ButtonGroup />
要么<ButtonGroup> </ButtonGroup>
以下是完整的代码运行:
import React, { Component } from 'react';
import './App.css';
class ButtonGroup extends Component{
render(){
return (<button onClick={this.countClick}>Count it up</button>);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
message:"state from constructor",
counter: 1
};
this.handleClick = this.handleClick.bind(this);
this.countClick = this.countClick.bind(this);
}
handleClick(e) {
this.setState( () => ({message:"state from click handler"}) )
}
countClick(e) {
this.setState( (prev, props) => ({counter: (prev.counter + 1)}))
}
render() {
return (
<div>
<div>
<h1>{this.state.message}</h1>
<h1>{this.state.counter}</h1>
</div>
<button onClick={this.handleClick}>Change it up</button>
<ButtonGroup />
</div>
);
}
}
export default App;
countClick()
。关注渲染后,如果要使用App组件countClick()
,则必须执行this.props.countClick
并将其作为<ButtonGroup countClick = {this.props.countClick} />
之类的道具传递给ButtonGroup [上面的完整代码只是解决你的渲染问题]这个道具取决于你的实现。答案 1 :(得分:0)
自定义组件应始终以大写字母(Pascal大小写)开头。所有以小写字母开头的组件都将被视为反应的内置组件,而不是用户定义的组件或自定义组件。
尝试将buttonGroup更改为ButtonGroup并进行检查。
同样在buttonGroup类中,您使用的是未定义的countClick方法。如果您希望使用App组件countClick方法,您应该执行this.props.countClick并将其作为<ButtonGroup countClick = {this.countClick} />