当我按下按钮时,我想发布一些内容(在屏幕上呈现)。 按下按钮不会出现任何错误,但也不会给出我期望的结果。我有新的反应。
import React, { Component } from 'react';
import './style.css';
export default class Main extends Component {
newBlog = () => {
return (
<div>
<Post name = "James" about = "about java" post = "javs is great for complex software apps"/>
</div>
);
}
render() {
return(
<div>
<button onClick = {this.newBlog}>Post-Blog</button>
</div>
);
}
}
class Post extends Component {
render() {
const { name, about, post} = this.props;
return(
<div className = "main">
<h2>{name}</h2>
<h2>{about}</h2>
<hr/><br/>
<p>{post}</p>
</div>
);
}
}
答案 0 :(得分:0)
按钮点击返回的JSX需要在某处呈现。您最好在按钮单击时设置可见状态,因为按钮上的onClick处理程序不会对您的案例中的返回值执行任何操作。请查看以下代码段
dim myVehicles as new list(of object)
dim myCar as new car
dim myBike as new bike
dim mySecondCar as new car
myVehicles.add(myCar)
myVehicles.add(myBike)
myVehicles.add(mySecondCar)
class Main extends React.Component {
state = {visible: false}
newBlog = () => {
return (
<div>
<Post name = "James" about = "about java" post = "javs is great for complex software apps"/>
</div>
);
}
toggleVisible = () => {
this.setState(prev => ({visible: !prev.visible}))
}
render() {
return(
<div>
{this.state.visible? this.newBlog(): null}
<button onClick = {this.toggleVisible}>Post-Blog</button>
</div>
);
}
}
class Post extends React.Component {
render() {
const { name, about, post} = this.props;
return(
<div className = "main">
<h2>{name}</h2>
<h2>{about}</h2>
<hr/><br/>
<p>{post}</p>
</div>
);
}
}
ReactDOM.render(<Main/>, document.getElementById('app'));
答案 1 :(得分:0)
你应该使用带有onClick事件的箭头功能。 尝试在主要组件的渲染
render() {
return(
<div>
{this.state.visible? this.newBlog(): null}
<button onClick ={() => this.toggleVisible}>Post-Blog</button>
</div>
)
};
答案 2 :(得分:0)
作为对你评论的回答。 如果我明白你的意思
import uuid from 'uuid/v4'; // get by npm install --save uuid || generate an unique id at each call
class Main extends React.Component {
constructor() {
super();
this.state = {
myBlog: [],
}
}
createNewBlog = () => {
var myPost = { name: 'John', about:'Javascript', post:"i'm john, i'll take about javascript"}
var currentMyBlog = this.state.myBlog;
currentMyBlog.push(myPost);
this.setState({myBlog: currentMyBlog});
};
render() {
return(
<div className=''>
{this.state.myBlog.map(post => (
<div key={uuid()}>
<Post name={post.name} about={post.about} post={post.post}/>
</div>
))}
<button onClick={ () => this.createNewBlog()}> Post blog</button>
</div>
)
}
};