【问题标题】:How to create button react component?如何创建按钮反应组件?
【发布时间】:2021-12-20 15:48:10
【问题描述】:

我创建了简单的 React 应用程序,需要添加按钮组件。不幸的是,我的代码不起作用。我该如何解决?按钮实现(React):

import React from 'react';

const Button = (props) => {
    return <button className="button">
        {props.children}
    </button>;
}

export { Button };

测试代码:

import React from 'react';
import { shallow } from 'enzyme';

import Button from './Button';

describe('Button', () => {
    /**

     * children - button text

     */

    it('Button with text', () => {
        const component = shallow(<Button>Button</Button>);

        expect(component.html()).toEqual('<button class="button">Button</button>');
    });
});

files in dir

测试错误:

 Expected: "<button class=\"button\">Button</button>"
 Received: null

【问题讨论】:

  • 你的意思是测试不工作或代码
  • 我的测试请求代码回答为 null 而不仅仅是一些东西

标签: javascript reactjs null frontend


【解决方案1】:

你可以试试这个,

it('Button with text', () => {
        const component = shallow(<Button>Button</Button>);

        expect(component.html()).toEqual('<button class=\"button\">Button</button>');
    });

【讨论】:

  • 相同的结果,收到:null
【解决方案2】:

这个导入行:

import Button from './Button';

要求构建从模块中获取 default 导出,但您正在将该组件导出到对象中。

所以要么:

export default Button;

或者:

import { Button } from './Button';

(我还建议在返回时在 JSX 周围添加括号,并导入一些特定于该组件的 CSS。)

function Button(props) {
  return (
    <button className="button">
      {props.children}
    </button>;
  );
}

export default Button;

【讨论】:

  • 谢谢你的工作
猜你喜欢
  • 1970-01-01
  • 2019-12-06
  • 2022-11-01
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 2021-11-08
  • 2022-01-22
  • 2023-04-05
相关资源
最近更新 更多