如何使用此函数{this.state.username}
更新此属性this.messageSubmit
中子组件内的状态值,以及如何重新呈现子渲染以显示已更改的状态值。请帮助我任何人如何更新我的状态值和聊天框,因为我是 reactjs的新手
这是我的子组件chatting.js
import React from "react";
export class Chatting extends React.Component{
constructor(props){
super(props);
this.state={
username: 'shiva'
}
this.messageSubmit=this.messageSubmit.bind(this);
this.messageTextBox=this.messageTextBox.bind(this);
}
messageTextBox(event){
this.setState=({
username :event.target.value
})
}
messageSubmit(){
console.log(this.setState.username);
}
render(){
return(
<div>
<div className="chat-decription">
<div className="rt">
<div className="talk-bubble tri-right btm-right">
<div className="talktext">
<p>Flush to the bottom right. Uses .btm-right only.</p>
</div>
</div>
</div>
<div className="fl">
<div className="talk-bubble tri-right btm-right">
<div className="talktext">
<p>Flush to the bottom right. Uses .btm-right only.</p>
</div>
</div>
</div>
<div className="rt">
<div className="talk-bubble tri-right btm-right">
<div className="talktext">
<p> {this.setState.username}</p>
</div>
</div>
</div>
<div className="fl">
<div className="talk-bubble tri-right btm-right">
<div className="talktext">
<p>Flush to the bottom right. Uses .btm-right only.</p>
</div>
</div>
</div>
</div>
<div className="chat-textfiled">
<input type="text" className="form-control text-form" onChange={this.messageTextBox}/>
<input type="button" value="submit" onClick={this.messageSubmit}/>
</div>
</div>
)
}
}
这是我的父类
import React from "react";
import {render} from "react-dom";
import {Default} from "./component/Default";
import {Chatting} from "./component/Chatting";
import {BrowserRouter as Router,Route,Link,Switch } from 'react-router-dom';
// import Background from '../images/person_img.png';
class App extends React.Component{
constructor(){
super();
}
render(){
return(
<Router>
<div className="container">
<div className="container-top">
<div className="col-lg-4 leftmenu-contact-bg">
<div className="searchbox">
<div className="textbox-bg">
<input type="text" className="form-control" placeholder="Search"/>
</div>
</div>
<div className="ex1">
<a href="/chattting">
<div className="left-list">
<div className="left-img"><i className="material-icons icon-color">person</i></div>
<div className="right-content">dgfg</div>
</div>
</a>
</div>
</div>
<div className="col-lg-8 row">
<Switch>
<Route exact path='/' component={Default} />
<Route exact path='/chattting' component={Chatting} />
</Switch>
</div>
</div>
</div>
</Router>
);
}
}
render(<App/>,document.getElementById('app'));
答案 0 :(得分:1)
setState
是一个功能。
你应该写:
this.setState({
username: event.target.value
});
此外,而不是
console.log(this.setState.username);
你应该写
console.log(this.state.username);
而且,而不是:
<p>{this.setState.username}</p>
你应该写
<p>{this.state.username}</p>
答案 1 :(得分:0)
除了@Rahamin的语法更正之外,还有一些指向代码的指针 -
setState
,因为它会进入无限递归函数调用堆栈。您可能会被误Maximum update depth exceeded
。console.log
会在排队和更新时为您提供所需的输出。最好在渲染本身中包含此类console.log
语句。