首页 > 解决方案 > 如何在 React 中将警报切换为常规消息

问题描述

我正在尝试更改 Dan Abraham 的代码并希望将警报切换到段落。只是想对 React 有所了解。

反应:

 function FancyBorder(props) {
   return ( <div className={'FancyBorder FancyBorder-' + props.color}> {props.children} </div> ); }

 function Dialog(props) {
   return (  <FancyBorder color="blue"> <h1 className="Dialog-title"> {props.title} </h1> <p className="Dialog-message"> {props.message} </p>
  {props.children} </FancyBorder> ); }

 class SignUpDialog extends React.Component {
   constructor(props) { 
     super(props);
       this.handleChange = this.handleChange.bind(this);
       this.handleSignUp = this.handleSignUp.bind(this);
       this.state = {login: ''}; }

     render() {
        return ( <Dialog title="Mars Exploration Program" message="How should we refer to you?">
    <input value={this.state.login} onChange={this.handleChange} /> <button onClick={this.handleSignUp}> Sign Me Up! </button> </Dialog> );
  }
 handleChange(e) { this.setState({login: e.target.value}); }

 handleSignUp() { alert(`Welcome aboard, ${this.state.login}!`); }
 }

 ReactDOM.render( <SignUpDialog />, document.getElementById('root') );

标签: javascriptreactjs

解决方案


像这样的东西:

function FancyBorder(props) {
  return (
    <div className={"FancyBorder FancyBorder-" + props.color}>
      {" "}
      {props.children}{" "}
    </div>
  );
}

function Dialog(props) {
  return (
    <FancyBorder color="blue">
      {" "}
      <h1 className="Dialog-title"> {props.title} </h1>{" "}
      <p className="Dialog-message"> {props.message} </p>
      {props.children}{" "}
    </FancyBorder>
  );
}

class SignUpDialog extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSignUp = this.handleSignUp.bind(this);
    this.state = {
      login: "",
      paragraphText: ""
    };
  }

  render() {
    return (
      <Dialog
        title="Mars Exploration Program"
        message="How should we refer to you?"
      >
        <input value={this.state.login} onChange={this.handleChange} />{" "}
        <button onClick={this.handleSignUp}> Sign Me Up! </button>{" "}
        <p>{this.state.paragraphText}</p>
      </Dialog>
    );
  }
  handleChange(e) {
    this.setState({ login: e.target.value });
  }

  handleSignUp() {
    this.setState({
      paragraphText: `Welcome aboard, ${this.state.login}!`
    });
  }
}

推荐阅读