如何使用ink react
安装 Ink 和 React
确保 Node.js 版本在 12 或更高版本。通过 npm 或 yarn 安装 Ink 和 React:
npm install ink react
创建 Ink 应用
创建一个新的 Ink 项目或在现有项目中添加 Ink 支持。使用以下命令初始化项目:
npx create-ink-app my-ink-app
cd my-ink-app
编写 Ink 组件
Ink 组件与 React 组件类似,但专为命令行界面设计。以下是一个简单的计数器示例:
import React, { useState, useEffect } from 'react';
import { render, Text } from 'ink';
const Counter = () => {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 100);
return () => {
clearInterval(timer);
};
}, []);
return <Text color="green">{count}</Text>;
};
render(<Counter />);
运行 Ink 应用
使用以下命令运行 Ink 应用:
node index.js
使用 Ink 内置组件
Ink 提供多个内置组件如 <Text>, <Box>, <Newline> 等。以下示例展示如何使用 <Box> 布局:
import { render, Text, Box } from 'ink';
const App = () => (
<Box flexDirection="column">
<Text color="red">Red Text</Text>
<Text color="blue">Blue Text</Text>
</Box>
);
render(<App />);
处理用户输入
使用 <TextInput> 组件处理用户输入:
import { render, Text, TextInput } from 'ink';
const Search = () => {
const [query, setQuery] = useState('');
return (
<>
<Text>Search:</Text>
<TextInput value={query} onChange={setQuery} />
<Text>You typed: {query}</Text>
</>
);
};
render(<Search />);
添加交互功能
通过 Ink 的 useInput hook 实现键盘交互:
import { render, useInput, Text } from 'ink';
const InteractiveApp = () => {
const [x, setX] = useState(0);
const [y, setY] = useState(0);
useInput((input, key) => {
if (key.leftArrow) setX(x => Math.max(0, x - 1));
if (key.rightArrow) setX(x => x + 1);
if (key.upArrow) setY(y => Math.max(0, y - 1));
if (key.downArrow) setY(y => y + 1);
});
return <Text>Position: {x},{y}</Text>;
};
render(<InteractiveApp />);
构建和发布
构建生产版本并发布到 npm:
npm run build
npm publish
调试 Ink 应用
使用 ink-testing-library 进行组件测试:
npm install --save-dev ink-testing-library
测试示例:
import { render } from 'ink-testing-library';
import { MyComponent } from './MyComponent';
test('displays correct output', () => {
const { lastFrame } = render(<MyComponent />);
expect(lastFrame()).toContain('Expected Text');
});





