ReactComponent Button值不会在我的反应应用上呈现

时间:2018-03-18 16:12:12

标签: reactjs

我有一个简单的React App正在进行中。当然,我的index.js文件看起来像这样:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

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

更深入,我的App.js文件声明了一个App extends Compoennt类,其中包含我要渲染的元素及其功能:

import React, { Component } from "react";
import logo from "./SmartTransit_logo.png";
import MyButton from "./components/MyButton";
import "./App.css";

import { isWallet, helloWorld } from "./services/neo-service";

class App extends Component {
  state = {
    inputValue: ""
  };
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Smart Transit Live Demo</h1>
        </header>

        <div style={{ width: 500, margin: "auto", marginTop: 10 }}>
            <MyButton
                buttonText="My Button"
                onClick={ params => {helloWorld();}}
            />
        </div>
      </div>
    );
  }
}

export default App;

来自MyButton的{​​{1}}声明:

/components/MyButton

最后,import React, { Component } from "react"; import PropTypes from "prop-types"; class MyButton extends Component { render() { return ( <button className="MyButton" value = {this.props.buttonText} > {this.props.children} </button> ); } } MyButton.propTypes = { buttonText: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, }; export default MyButton; 的声明是这样完成的(注意:helloWorld()是我正在使用的npm包):

neon-js

我的问题是生成的Button没有呈现其import { wallet } from "@cityofzion/neon-js"; export function isWallet(address) { console.log(wallet.isAddress(address)); return wallet.isAddress(address); } export function helloWorld() { console.log("Hello world"); return 1; } 文本,虽然它获得了value代码就好了但它看起来是空的!

enter image description here

不仅如此,按下它不会在控制台中记录“Hello World”,因为它应该与它的CSS功能断开连接。

对我做错了什么的想法?

3 个答案:

答案 0 :(得分:1)

  1. 按钮不会获​​得“价值”道具。 button元素内部的文本就是它的文本。
  2. 该按钮似乎接受将子项用作按钮文本,但实际上没有子项传递给它。 this.props.children是呈现组件时JSX标记之间的内容。
  3. React不会自动将事件处理程序添加到元素。你必须自己传递它们才能正确触发它们。
  4. 考虑到这一点,以下是您应该在App中呈现按钮的方式:

    <MyButton onClick={() => helloWorld()}>
      My Button
    </MyButton>
    

    以下是MyButton代码的外观:

    class MyButton extends Component {
      render() {
        return (
          <button className="MyButton" onClick={this.props.onClick}>
            {this.props.children}
          </button>
        )
      }
    }
    

    如您所见,不再需要buttonText道具;这就是children道具的用途。

答案 1 :(得分:0)

当您要使用super(props)时,您需要在类构造函数中定义this.props

constructor(props) {
    super(props);
}

MyButton组件中定义它。

答案 2 :(得分:0)

问题是,你没有从mybutton组件调用onClick方法,而按钮在它的开始和结束标记之间取值。

使用此代码:

this.props.onClick()}&GT; {this.props.buttonText}

相关问题