import React, { useState } from 'react';
import { View, Text, Button, Alert } from 'react-native';
 
const DeleteConfirmation = ({ onDelete }) => {
  const [isVisible, setIsVisible] = useState(false);
 
  const showDeleteConfirmation = () => {
    setIsVisible(true);
  };
 
  const hideDeleteConfirmation = () => {
    setIsVisible(false);
  };
 
  const handleDelete = () => {
    onDelete();
    hideDeleteConfirmation();
  };
 
  return (
    <View>
      <Button title="Delete" onPress={showDeleteConfirmation} />
      {isVisible && (
        <Alert
          title="Delete Item?"
          message="Are you sure you want to delete this item?"
          buttons={[
            { text: 'Cancel', onPress: hideDeleteConfirmation },
            { text: 'Delete', onPress: handleDelete },
          ]}
        />
      )}
    </View>
  );
};
 
export default DeleteConfirmation;

这段代码使用了React Native的Alert组件来实现一个简单的删除确认功能。用户点击按钮后会弹出一个警告框,询问用户是否确定要删除项目。如果用户确认删除,onDelete回调函数会被调用,并且删除确认对话框会被关闭。这个例子展示了如何使用React Hooks和React Native组件来实现一个简单的交互逻辑。

在React中,组件间传递数据通常使用以下方法:

  1. 父组件向子组件传递数据:通过props(属性)。
  2. 子组件向父组件传递数据:通过回调函数(callbacks)。
  3. 兄弟组件间传递数据:使用共享的上下文(Context)或状态管理库(如Redux)。

以下是一个父组件向子组件传递数据的例子:




// 父组件
import React from 'react';
import ChildComponent from './ChildComponent';
 
const ParentComponent = () => {
  const data = "这是父组件的数据";
 
  return (
    <ChildComponent childData={data} />
  );
};
 
export default ParentComponent;
 
// 子组件
import React from 'react';
 
const ChildComponent = ({ childData }) => {
  return (
    <div>
      <p>{childData}</p>
    </div>
  );
};
 
export default ChildComponent;

以下是一个子组件向父组件传递数据的例子:




// 父组件
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
 
const ParentComponent = () => {
  const [message, setMessage] = useState("");
 
  const handleChange = (newMessage) => {
    setMessage(newMessage);
  };
 
  return (
    <div>
      <p>{message}</p>
      <ChildComponent onChange={handleChange} />
    </div>
  );
};
 
export default ParentComponent;
 
// 子组件
import React from 'react';
 
const ChildComponent = ({ onChange }) => {
  const sendDataToParent = (e) => {
    onChange(e.target.value);
  };
 
  return (
    <input type="text" onChange={sendDataToParent} />
  );
};
 
export default ChildComponent;

这些例子展示了React组件间数据传递的基本方法。




// 导入必要的库
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
 
// 定义一个React包用于集成
class CustomReactPackage : ReactPackage {
    override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
        // 返回需要注册的原生模块列表
        return emptyList<NativeModule>()
    }
 
    override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
        // 返回需要注册的原生UI管理器列表
        return emptyList<ViewManager<*, *>>()
    }
}
 
// 在主应用中注册React包
class MyApplication : Application {
    override fun onCreate() {
        super.onCreate()
        SoLoader.init(this, /* native exopackage */ false)
 
        val packages = ArrayList<ReactPackage>()
        packages.add(CustomReactPackage()) // 添加自定义React包
 
        // 初始化React Native
        ReactNativeHost(application).getReactInstanceManager()
            .builder()
            .setApplication(application)
            .setBundleAssetName("index.android.bundle")
            .setJSMainModulePath("index.android")
            .addPackages(packages)
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build()
            .initialize()
    }
}
 
// 优化React Native的启动时间
val mReactRootView: ReactRootView = ReactRootView(context)
mReactRootView.startReactApplication(
    reactInstanceManager.currentReactContext
        .getJSModule(AppRegistry::class.java)
        .getAppKeys(),
    "MyReactNativeApp" // 你的React Native应用的名字
)

这个代码示例展示了如何在Android应用中集成自定义的React Native包,并在Application类的onCreate方法中初始化React Native。同时,它也演示了如何优化React Native的启动时间,通过直接使用已有的React上下文来加载应用。




import React, { useState } from 'react';
 
function Counter() {
  const [count, setCount] = useState(0);
 
  // 使用 useRef 来保存可变的计数器状态
  const latestCount = useRef(count);
 
  useEffect(() => {
    // 更新最新的状态值
    latestCount.current = count;
  });
 
  const asyncIncrement = () => {
    setTimeout(() => {
      // 读取最新的状态值
      setCount(latestCount.current + 1);
    }, 1000);
  };
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={asyncIncrement}>异步增加</button>
    </div>
  );
}
 
export default Counter;

这段代码使用了React的函数组件和hooks API来实现一个计数器功能。它展示了如何使用useRef来保存一个可以在组件的整个生命周期内更新的状态值,并且展示了如何在异步函数中正确地使用这个状态值。这是学习React中状态管理和异步操作的一个很好的例子。




import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
import Adjust, { AdjustEvent, AdjustConfig } from 'react-native-adjust';
 
class App extends Component {
  componentDidMount() {
    this.initAdjust();
    this.trackSimpleEvent();
  }
 
  initAdjust() {
    // 初始化Adjust SDK
    AdjustConfig.create({
      appToken: 'YOUR_APP_TOKEN', // 替换为你的App Token
      environment: AdjustConfig.EnvironmentSandbox, // 使用沙箱环境进行开发测试
      // 如果需要,可以添加默认事件数据
      defaultTracker: 'YOUR_TRACKER'
    });
 
    AdjustConfig.setLogLevel(AdjustConfig.LogLevelVerbose); // 设置日志级别
    AdjustConfig.setProcessName('com.adjust.examples'); // 设置进程名称
 
    let adjustConfig = AdjustConfig.build();
    Adjust.appDidLaunch(adjustConfig);
  }
 
  trackSimpleEvent() {
    // 创建并追踪一个简单的事件
    let adjustEvent = new AdjustEvent('simpleEvent');
    adjustEvent.setRevenue(0.01, 'EUR'); // 设置收益信息
    Adjust.trackEvent(adjustEvent);
  }
 
  render() {
    return (
      <Text>Adjust Example App</Text>
    );
  }
}
 
AppRegistry.registerComponent('AdjustExample', () => App);

这段代码展示了如何在React Native应用程序中初始化Adjust SDK并发送一个简单事件。在实际应用中,你需要替换 'YOUR_APP_TOKEN''YOUR_TRACKER' 为你从Adjust面板获取的真实值。此外,对于不同的环境(开发、生产),你可能需要根据需要切换环境配置。这个例子还展示了如何设置日志级别和进程名称,这些都是开发者可选的配置项。

在React中,EventBus或者可以理解为自定义事件系统,可以用于组件间通信。以下是一个简单的例子,展示了如何使用EventBus传递参数:




import React from 'react';
 
// 创建一个简单的Event Bus
const EventBus = {
  listeners: {},
  on(event, callback) {
    this.listeners[event] = this.listeners[event] || [];
    this.listeners[event].push(callback);
  },
  emit(event, ...args) {
    if (this.listeners[event]) {
      this.listeners[event].forEach(callback => callback(...args));
    }
  }
};
 
// 使用EventBus的组件
class ComponentA extends React.Component {
  notifyB = (message) => {
    EventBus.emit('ComponentAEvent', message);
  };
 
  render() {
    return (
      <div>
        <button onClick={() => this.notifyB('Hello from Component A!')}>
          Notify Component B
        </button>
      </div>
    );
  }
}
 
class ComponentB extends React.Component {
  componentDidMount() {
    EventBus.on('ComponentAEvent', this.handleEventFromA);
  }
 
  componentWillUnmount() {
    EventBus.on('ComponentAEvent', this.handleEventFromA);
  }
 
  handleEventFromA = (message) => {
    alert(`Event received in Component B with message: ${message}`);
  };
 
  render() {
    return <div>Component B is listening for events</div>;
  }
}
 
// 应用组件
const App = () => (
  <>
    <ComponentA />
    <ComponentB />
  </>
);
 
export default App;

在这个例子中,我们定义了一个简单的EventBus对象,它有on方法用于监听事件,emit方法用于触发事件,并传递参数。ComponentA有一个按钮,当点击时,它会通过EventBus发送一个事件及消息给ComponentBComponentB在挂载时开始监听ComponentA发出的事件,并处理接收到的消息。




import React, { useState, useEffect, useRef } from 'react';
 
function ExampleComponent() {
  const [count, setCount] = useState(0);
  const didMountRef = useRef(false);
 
  useEffect(() => {
    didMountRef.current = true;
    return () => {
      didMountRef.current = false;
    };
  }, []);
 
  const handleIncrement = () => {
    if (didMountRef.current) {
      setCount(count + 1);
    }
  };
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}
 
export default ExampleComponent;

这个代码示例展示了如何在React 18组件中使用useRef来避免在未挂载的组件上执行状态更新。这是一个常见的优化模式,可以防止组件在卸载后的点击或者定时器中产生的不必要的状态更新,从而提高了应用的响应性和性能。




import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Button } from 'antd';
 
// 导入样式文件
import './style.less';
 
// 自定义组件
export default class CustomComponent extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    onClick: PropTypes.func,
    text: PropTypes.string,
  };
 
  static defaultProps = {
    className: '',
    onClick: () => {},
    text: 'Click Me',
  };
 
  handleClick = () => {
    const { onClick } = this.props;
    onClick();
  };
 
  render() {
    const { className, text } = this.props;
    const classes = classNames('custom-component', className);
 
    return (
      <div className={classes}>
        <Button onClick={this.handleClick}>{text}</Button>
      </div>
    );
  }
}

这个代码实例展示了如何在React中实现一个简单的组件,该组件接收一些属性,并使用classNames库来处理条件类名的应用,以及使用PropTypes进行属性类型检查。同时,它使用了PureComponent来优化渲染性能,并使用onClick属性来处理点击事件。最后,它展示了如何导入和使用来自Ant Design的Button组件。




import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Dropdown, Icon } from 'semantic-ui-react';
 
interface LanguageOptionProps {
  text: string;
  value: string;
  image: string;
}
 
const LanguageOptions: LanguageOptionProps[] = [
  { text: 'English', value: 'en', image: '../../images/en.png' },
  { text: '中文', value: 'zh', image: '../../images/cn.png' }
];
 
const TopNav: React.FC = () => {
  const { t, i18n } = useTranslation();
  const [language, setLanguage] = useState(i18n.language);
 
  const handleLanguageChange = (_, data: any) => {
    const { value } = data;
    i18n.changeLanguage(value);
    setLanguage(value);
  };
 
  return (
    <div className="topnav">
      <div className="topnav-wrapper">
        <Link to="/" className="topnav-logo">
          <img src="../../images/logo.png" alt="Logo" />
        </Link>
        <div className="topnav-menu">
          <Link to="/" className="item">{t('Home')}</Link>
          <Link to="/about" className="item">{t('About')}</Link>
          <Link to="/contact" className="item">{t('Contact')}</Link>
          <Dropdown
            text={t('Language')}
            icon={<Icon name="world" />}
            className="language-dropdown"
            options={LanguageOptions.map(option => ({
              ...option,
              text: t(option.text),
              image: { avatar: true, src: option.image }
            }))}
            onChange={handleLanguageChange}
            value={language}
          />
        </div>
      </div>
    </div>
  );
};
 
export default TopNav;

这个代码实例使用了React Hooks和TypeScript来创建一个响应式的头部导航组件,其中包括一个下拉菜单来切换语言。它使用了react-i18next库来处理国际化,并且展示了如何使用Dropdown组件从semantic-ui-react库来创建语言切换功能。

React Native 自动更新库的推荐是 react-native-code-push。这是微软提供的一个应用热更新服务,可以让你在不发布新版本应用的情况下,推送代码更新或者修复bug。

以下是如何使用 react-native-code-push 的基本步骤:

  1. 安装 react-native-code-push 库。



npm install --save react-native-code-push

或者如果你使用 yarn:




yarn add react-native-code-push
  1. 链接原生平台的 react-native-code-push 模块。



react-native link react-native-code-push
  1. 配置 code-push 的 deployment keys。

在你的 app.json 或者 package.json 文件中,添加对应平台的 deployment key。




{
  "codePush": {
    "deploymentName": {
      "ios": "your_ios_deployment_key",
      "android": "your_android_deployment_key"
    }
  }
}
  1. 在你的 React Native 代码中使用 code-push

例如,你可以在你的入口文件 index.js 中使用如下代码来检查更新:




import CodePush from 'react-native-code-push';
 
CodePush.sync({
  updateDialog: true, // 可选,是否显示对话框提示用户更新
  installMode: CodePush.InstallMode.IMMEDIATE // 可选,应用更新后是否立即重启
});

更多高级用法和配置选项,可以查看 react-native-code-push 的官方文档。