javascript - 在 React 中重新渲染类

标签 javascript reactjs

React 新手,我正在测试编写一个小程序,您可以在列表中选择一个名称,然后应该显示一条谚语。事件处理程序handleAuthorClick被调用,setState也被调用,但新文本没有显示。

为什么?

class AuthorList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: -1,
      text: "When in Rome do as the Romans",
    }
  }

  handleAuthorClick()
  {
       let txt = "initial value";
       var sel = document.getElementById("author-list"); 
       switch (parseInt(sel.value))
        {
          case 12 : txt = "When in Rome do as the Romans"; break;
          case 33: txt = "If you tell the truth, you don't have to remember anything.";break;
          case 256: txt = "History will be kind to me for I intend to write it";break;
          default:;
        }
       this.setState({text: txt});
  }

  render() {
      return (
        <div className="author-list">
          <h2>Author List</h2>
          <select id='author-list' name='author-list' size='15' onClick={() => this.handleAuthorClick()>
             <option value="12">Unknown</option>
             <option value="33">Mark Twain</option>
             <option value="256">Winston Churchill</option>
          </select>
          <h2>Proverbs</h2>
          {this.props.text}
        </div>
      );
    }
  }

class ProVerbMain extends React.Component {
      render() {
      return (
        <div className="proverb">
          <h1>Dans proverbs</h1>
          <div className="author-list">
            <AuthorList text = 'Initial value'/>
          </div>
        </div>
      );
    }
  }

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

最佳答案

使用 this.state.text 而不是 this.props.text,因为它是组件的本地状态。当您使用 this.props.text 时,您的组件不知道新渲染的新状态。 您应该在选择选项中使用 onChange() 事件而不是 onClick()

关于javascript - 在 React 中重新渲染类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58607931/

相关文章:

javascript - 寓言文档 Pojo 属性

javascript - 使用 Polymer.dom(this.root).querySelector 无法在 Polymer 元素中找到复选框元素

javascript - React Native 滑出面板和 ScrollView

reactjs - 不同的布局 - React Router v4

reactjs - React Router Dom Redirect 需要刷新页面才能工作

javascript - 如果事件位于元素的 id 上而不是 "generic"标签上,则使用 e.preventDefault () 是否错误?

javascript - 不删除 contenteditable 设置为 true 的 div 中的子元素

javascript - 是否可以使用 Javascript 获取相邻表行中的项目值?

reactjs - 如何修复 "export ' React'(导入为 'React')在 'react' 中未找到“React js 错误”

reactjs - 如何在带有 typescript 的 React 中正确使用 useState 钩子(Hook)?