gpt4 book ai didi

javascript - ReactJS如何将子组件值传递给父组件

转载 作者:行者123 更新时间:2023-12-01 01:51:11 25 4
gpt4 key购买 nike

我有以下代码

chat.js

import React from 'react';
import '../styles/Chat.css';
import Web from '../services/Web';

class Chat extends React.Component {

constructor(props) {
super(props);

this.state = {
msg:''
};
this.sendMessage = this.sendMessage.bind(this);
}

sendMessage () {
this.props.updatecommentText(this.refs.newText.value, this.props.index);
this.setState({ msg: '' });
}

render() {
return (
<div className="Chat-container">
<div className="Chat-row">
<div className="Chat-column">
<div className="Chat-card">
<div className="Chat-body">
<div className="Chat-title">React Based Chatbot</div>
<div className="Chat-messages">
{ this.props.children }
</div>
</div>
<div className="Chat-footer">
<textarea className="Chat-input" ref="newText"></textarea>
<button className="Chat-submit" onClick={this.sendMessage} defaultValue={ this.props.children }>Send</button>
</div>
</div>
</div>
</div>
</div>
);
}
}


export default Chat;

Web.js

import React, { Component } from 'react';
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import Chat from '../components/Chat';

class Web extends React.Component {

constructor(props){
super(props);

this.state = {
messages:["Hi, How can I help you ?"
]
};
this.sendtobot = this.sendtobot.bind(this);
}

sendtobot(newText, i){
var arr = this.state.messages
arr.push(newText)
this.setState({messages: arr})
}

eachMessage(message, i){
return (<Chat key={i} index={i} updatecommentText={ this.sendtobot.bind(this) }>{ message }</Chat>);
}

render(){
return(
<div>
{this.state.messages.map(this.eachMessage.bind(this))}
</div>
)
}

}

export default Web;

我想从 Chat.js 获取输入并将其发送到 Web.js 并将该值推送到数组消息,然后再次在Chat.js

中的 this.props.children

但是,在运行代码时,我收到错误 this.props.updatecommentText 不是函数。有人可以帮我解决这个问题吗?

最佳答案

您已绑定(bind) this.sendtobot 两次。它应该只在构造函数中。像这样

eachMessage(message, i){
return (
<Chat key={i} index={i} updatecommentText={this.sendtobot}>
{ message }
</Chat>
);
}

关于javascript - ReactJS如何将子组件值传递给父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51494484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com