最近,我在 react nexus 上发表了关于“辅助功能和电视应用程序”的演讲。我不断收到的一个问题是:“作为一名 reactjs 开发人员,开始使用 react native 有多容易?”
简而言之,对于 reactjs 开发者来说,从 react native 开始会很容易。
在这篇博客中,我将分享 reactjs 开发人员可以在 react native 中使用的五件事。
1. 组件
在 react native 中,您将像在 reactjs 中一样创建组件。概念和最佳实践保持不变。
import react from 'react';
import { view, text } from 'react-native';
const greetingcomponent = () => {
return (
<view><text>hello, neha!</text></view>
);
};
export default greetingcomponent;
2. 道具和状态
在 react native 中,props 和 state 的工作方式与 reactjs 中相同。要在组件之间进行通信,您将使用 props。要更新值,您将使用状态。
import react from 'react';
import { view, text } from 'react-native';
const greetingcomponent = ({ name }) => {
return (
<view><text>hello, {name}!</text></view>
);
};
export default greetingcomponent;
3. 挂钩
就像在 reactjs 中一样,您可以使用 react native 中的所有钩子,例如 usestate()、usememo()、useeffect() 等。此外,您还可以创建自己的自定义钩子。
import react, { usestate } from 'react';
import { view, text, button, stylesheet } from 'react-native';
const greetingcomponent = () => {
const [name, setname] = usestate('john');
const changename = () => {
setname('jane');
};
return (
<view style="{styles.container}"><text>hello, {name}!</text><button title="change name" onpress="{changename}"></button>
</view>
);
};
export default greetingcomponent;
4. 测试
如果您是 react 测试库的粉丝,好消息是您可以使用相同的库在 react native 中进行测试。
import react from 'react';
import { render, fireevent } from '@testing-library/react-native';
import greetingcomponent from './greetingcomponent';
test('it renders correctly and changes name on button press', () => {
// render the component
const { getbytext } = render(<greetingcomponent></greetingcomponent>);
// assert initial state
expect(getbytext('hello, john!')).tobetruthy();
// find the button and simulate a press
const button = getbytext('change name');
fireevent.press(button);
// assert that the name has changed
expect(getbytext('hello, jane!')).tobetruthy();
});
5.jsx
在 react native 中,有一些组件可用于在 jsx 中创建视图。但是,在 reactjs 中,您可以使用任何有效的 html dom 元素。
import react from 'react';
import { view, text } from 'react-native';
const greetingcomponent = () => {
return (
<view><text>hello, neha!</text></view>
);
};
export default greetingcomponent;
快乐学习!!