替换内容中的字符串

问题描述 投票:0回答:2

看看我的Chat.js内容:

import React, { Component } from "react";

class Chat extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: [],
      message: ""
    };
  }
  submitMessage(event) {
    event.preventDefault();
    this.setState(state => ({
      messages: [<li>{this.state.message}</li>, ...state.messages]
    }));
    this.setState({
      message: ""
    });
  }
  render() {
    return (
      <>
        <div class="container py-3">
          <h2 className="text-center mb-4">Simple Chat</h2>
          <form
            onSubmit={e => {
              this.submitMessage(e);
            }}
          >
            <input
              type="text"
              className="form-control"
              placeholder={"Enter your message..."}
              value={this.state.message}
              onChange={e => this.setState({ message: e.target.value })}
            />
            <button type="submit" className="btn btn-success mt-2">
              Send Message
            </button>
          </form>

          <div className="container border mt-2">
            <ul className="group-list mt-3 pt-2">{this.state.messages}</ul>
          </div>
        </div>
      </>
    );
  }
}

export default Parent;

也是,这是我的示例https://codesandbox.io/s/objective-water-1e8uq

当有人用@@>]输入用户名时,我需要替换用户链接

例如,这是我的邮件内容:

Are you good @Daniel ? 

我需要将以上消息转换为以下内容:

Are you good <a href="#">@Daniel</a> ? 

我使用react-router-dom,所以我需要用以下代码替换链接:

例如:

<Router>
   <Link to={ '#'} onClick={() => {this.example()}}>
    @Daniel
  </Link>
</Router>;

看看我的Chat.js内容:从“ react”导入React,{组件};类Chat扩展了Component {构造函数(props){super(props); this.state = {消息:[],...

reactjs events replace chat
2个回答
1
投票

应该用字符串替换来完成:

// This is to have as tag "Are you good <a href="#">@Daniel</a> ?" (with @ in the username)
const replacementReg = /(@[a-zA-Z0-9]+)/g;
// This is to have as tag "Are you good <a href="#">Daniel</a> ?" (without @ in the username)
const replacementReg = /@([a-zA-Z0-9]+)/g;

function decorateWithLink(text) {
   text.replace(replacementReg, replaced => `<a href="#"> ${replaced} </a>`);
}

1
投票

我已经更新了您的SubmitMessage函数,这里是代码:

© www.soinside.com 2019 - 2024. All rights reserved.