bandpass-filter 相关问题


SQLAlchemy 添加子查询作为 OR 子句

我有一个子查询: sub_query = db.query(Table1.id).filter(Table1.id.in_(db.query(Table2.ref_col).filter(Table2.col1 == '值'))) 基本查询是 查询 = db.query(Table1).filter(Table1.col1 == '


SecurityException:不允许启动服务Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (有额外功能)}

我尝试从 Google 获取我的 GCM 注册 ID。 我的代码: 字符串SENDER_ID =“722*****53”; /** * 向 GCM 服务器异步注册应用程序。 * * 存储注册信息... 我尝试从 Google 获取我的 GCM 注册 ID。 我的代码: String SENDER_ID = "722******53"; /** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over // HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the // device will send // upstream messages to a server that echo back the message // using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } 我收到错误: 03-01 19:15:36.261: E/AndroidRuntime(3467): FATAL EXCEPTION: AsyncTask #1 03-01 19:15:36.261: E/AndroidRuntime(3467): java.lang.RuntimeException: An error occured while executing doInBackground() 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$3.done(AsyncTask.java:299) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.lang.Thread.run(Thread.java:841) 03-01 19:15:36.261: E/AndroidRuntime(3467): Caused by: java.lang.SecurityException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (has extras) } without permission com.google.android.c2dm.permission.RECEIVE 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.app.ContextImpl.startServiceAsUser(ContextImpl.java:1800) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.app.ContextImpl.startService(ContextImpl.java:1772) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.content.ContextWrapper.startService(ContextWrapper.java:480) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.google.android.gms.gcm.GoogleCloudMessaging.b(Unknown Source) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.google.android.gms.gcm.GoogleCloudMessaging.register(Unknown Source) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.example.gcm.DemoActivity$1.doInBackground(DemoActivity.java:177) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.example.gcm.DemoActivity$1.doInBackground(DemoActivity.java:1) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$2.call(AsyncTask.java:287) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 03-01 19:15:36.261: E/AndroidRuntime(3467): ... 4 more 这是我的清单: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.manyexampleapp" android:installLocation="preferExternal" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.example.manyexampleapp.c2dm.permission.RECEIVE" /> <uses-permission android:name="com.example.manyexampleapp.gcm.permission.C2D_MESSAGE" /> <permission android:name="com.example.manyexampleapp.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <application android:name="com.zoomer.ifs.BaseApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name="com.zoomer.ifs.MainActivity" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden|screenSize" android:launchMode="singleTop"> <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <!-- PUSH --> <!-- WakefulBroadcastReceiver that will receive intents from GCM services and hand them to the custom IntentService. The com.google.android.c2dm.permission.SEND permission is necessary so only GCM services can send data messages for the app. --> <receiver android:name="com.example.gcm.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <!-- Receives the actual messages. --> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="com.example.manyexampleapp" /> </intent-filter> </receiver> <service android:name="com.example.gcm.GcmIntentService" /> <activity android:name="com.example.gcm.DemoActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- DB --> <activity android:name="com.example.db.DbActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.http.RestGetActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" > </activity> <activity android:name="com.example.fb.FacebookLoginActivity" android:label="@string/app_name" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.example.http.SendFeedbackActivity" android:label="@string/app_name" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.zoomer.general.SearchNearbyOffersActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.facebook.LoginActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.manyexampleapp.StoresListActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.fb.ShareActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.notifications.NotificationsActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.fb2.no_use.MainActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.zoomer.offers.OffersListActivity" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.example.http.SearchNearbyOffersActivity" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <service android:name="com.example.geo.LocationService" android:enabled="true" /> <receiver android:name="com.example.manyexampleapp.BootReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="com.example.manyexampleapp.LocationService.LOCATION_BROAD_MSG" /> </intent-filter> </receiver> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id" /> </application> </manifest> 改变 <uses-permission android:name="com.example.manyexampleapp.c2dm.permission.RECEIVE" /> 到 <!-- This app has permission to register and receive data message. --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 您收到异常是因为您尚未定义所需的权限 如果应用程序开发后安装了播放服务, 可能会发生 com.google.android.c2dm.permission.RECEIVE 权限已被授予但 android 仍在抱怨同样的错误。 在这种情况下,您必须完全重新安装开发的应用程序才能使此权限发挥作用。 我认为你必须检查 Kotlin 版本兼容性。


Excel FILTER 公式在条件中使用溢出范围

我无法使用溢出范围使 FILTER 公式发挥作用。这是一个示例场景: 我在 E2 中有一个溢出范围,它为我提供了我想要查找的数字列表。 ...


Struts 2 与 Apache Shiro 集成时如何显示结果页面

使用: struts2 2.5.10, 春天 4.x, struts2-spring-插件2.5.10, 希罗1.4.0, Shiro-Spring 1.4.0。 网络.xml: 使用: struts2 2.5.10, 春季 4.x, struts2-spring-插件2.5.10, 四郎1.4.0, shiro-spring 1.4.0. web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <!-- shiro filter mapping has to be first --> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> beanx.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean name="loginAction" class="example.shiro.action.LoginAction" > </bean> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="filterChainDefinitions"> <value> /login.jsp = authc /logout = logout /* = authc </value> </property> </bean> <bean id="iniRealm" class="org.apache.shiro.realm.text.IniRealm"> <property name="resourcePath" value="classpath:shiro.ini" /> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="iniRealm" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans> struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" extends="struts-default"> <action name="list" class="loginAction" method="list"> <result name="success">/success.jsp</result> <result name="error">error.jsp</result> </action> </package> </struts> index.jsp: <body> <s:action name="list" /> </body> login.jsp 看起来像: <form name="loginform" action="" method="post"> <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr> <td>Username:</td> <td><input type="text" name="username" maxlength="30"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" maxlength="30"></td> </tr> <tr> <td colspan="2" align="left"><input type="checkbox" name="rememberMe"><font size="2">Remember Me</font></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="submit" value="Login"></td> </tr> </table> </form> LoginAction.list(): public String list() { Subject currentUser = SecurityUtils.getSubject(); if(currentUser.isAuthenticated()) {System.out.println("user : "+currentUser.getPrincipal()); System.out.println("You are authenticated!"); } else { System.out.println("Hey hacker, hands up!"); } return "success"; } shiro.ini: [users] root=123,admin guest=456,guest frank=789,roleA,roleB # role name=permission1,permission2,..,permissionN [roles] admin=* roleA=lightsaber:* roleB=winnebago:drive:eagle5 index.jsp、login.jsp、success.jsp放在webapp下 我想要的是:输入LoginAction.list()需要进行身份验证,如果登录成功,则运行LoginAction.list()并返回"success"然后显示定义为Struts操作结果的success.jsp。 现在登录成功后可以执行LoginAction.list(),但是success.jsp不显示,浏览器是空白页面。 为什么? 我找到了原因:我在index.jsp中使用了<s:action name="list" />,但是struts文档说如果我们想用<s:action>看到结果页面,那么我们必须将其属性executeResult设置为true,即就像<s:action name="list" executeResult="true"/>。 在我看来,这有点奇怪,这个属性默认应该是 true。 有一个示例,您应该如何使用 Shiro applicationContext.xml 进行配置: <property name="filterChainDefinitions"> <value> # some example chain definitions: /admin/** = authc, roles[admin] /** = authc # more URL-to-FilterChain definitions here </value> </property> 以 /admin/ 开头的 URL 通过角色 admin 进行保护,任何其他 URL 均不受保护。如果 Struts 操作和结果 JSP 不在受保护区域中,则会显示它们。


React 中的filter() 和map() 数据到单选按钮

我正在从 API 获取以下格式的数据: const 汽车属性 = [ { "key": "品牌", “价值观”:[ { ...


数组文字缺少一行或多行的值

=SORT(UNIQUE({QUERY(LAMBDA(z,filter(z,index(z,,12))=max(index(z,,12))))(IMPORTRANGE("1madkVso_zaoU9MH2gvtVlTaT2iJ9nMcCxS8ux0Vpz14", "概述!A2 :Z")),"选择 Col1,Col2,Col3,...


为什么我的文本要应用透明度?

我在透明背景上有文本,如下所示: http://jsfiddle.net/L9ggc06c/ 然而,文本仍然应用透明度。 #内容a:悬停.text p{ -ms-filter: "progid:


python3 使用请求时出错:URL 带有空格

我想对 Prolin Smart Suite API 进行 API 调用。使用 Postman 我可以成功完成此操作,调用必须如下所示: https://myserver.mydomain.net:5181/odata/ConfigurationItems?$filter=


如何添加 django-filter Rangefilter 类?

我尝试将引导类添加到价格范围过滤器中,但我不能, 导入 django_filters 从 panel.models 导入产品、类别、尺寸、TopNote、BaseNote、MidNote 从 django 导入表单 班级


C:CS50x - 第 4 周 - 筛选更多:2D 数组大小语法

我无法理解二维数组索引的语法。 (*图像)[宽度] 下面是 ProblemSet Filter-more, Week 3, cs50x 的部分分发 C 代码。代码不是我写的,而是...


Graph Api 多重过滤以获取最近 30 天上次登录的用户

我正在尝试使用图形 API 构建一个请求,以获取过去 30 天内未登录的所有用户。和: $URL =“https://graph.microsoft.com/v1.0/users?`$filter=signInActivity/lastSignInDateT...


Google 表格:插入单元格变量以确定选项卡名称

我希望让我的 Google 工作表拉入一个随机选项卡来填充其字段。我有一个 =RANDBETWEEN 给我一个数字,我希望有类似的东西: =FILTER('故事 1'!2:2,'故事 1'!2:...


无法解析 Microsoft graph 的 url 字符串,因为使用 Invoke-MSGraphRequest 命令和查询参数

我无法使用当前 URL 进行解析和调用,因为当我使用 $filter 和 $select 查询参数时,它会破坏字符串,但它在 Postman 中工作得很好,并为我提供了我需要的所有数据。


向垫子表添加额外的行

所以我有一张垫子桌 所以我有一张垫子桌 <mat-table class="table" cdkDropList cdkDropListOrientation="horizontal" (cdkDropListDropped)="tableDrop($event)" [dataSource]="tableDataSource"> <ng-container *ngFor="let column of columns; let i = index" [matColumnDef]="column.name"> <mat-header-cell *matHeaderCellDef cdkDrag dkDragLockAxis="x" cdkDragBoundary="mat-header-row"> {{ column.title }} </mat-header-cell> <mat-cell *matCellDef="let element"> {{ element[column.name] }} </mat-cell> </ng-container> <mat-header-row class="tableHeader" *matHeaderRowDef="tableDisplayedColumns" #tableHeaderRow> </mat-header-row> <mat-row class="tableRow" *matRowDef="let row; columns: tableDisplayedColumns;" [class.selected-row]="tableSelectedRows.has(row)" (click)="selectUnselectRow(row)"> </mat-row> </mat-table> 但我需要在表标题下为相应的行过滤器添加一行。我尝试在标题和实际行声明之间添加 <mat-row> ,但是由于过滤器是不同的输入(例如数字、自动完成选择和多选),我无法 *ngFor 它们(而且我不是当然我是否能够) 编辑:忘记发布过滤器 HTML <div class="filterGroup"> <mat-form-field class="filterField"> <input matInput type="number" (keydown)="updateManualPage(1)" placeholder="Filter za param1" formControlName="filterParam1"> </mat-form-field> <mat-form-field class="filterField"> <input matInput (keydown)="updateManualPage(1)" placeholder="Filter za param2" formControlName="filterParam2" [matAutocomplete]="autoSingleSelect"> <mat-autocomplete #autoSingleSelect="matAutocomplete" class="filterSelect" panelClass="filterSelect"> <mat-option *ngFor="let option of dropdownSingleFilteredOptions | async" [value]="option.param2"> {{option.param2}} </mat-option> </mat-autocomplete> </mat-form-field> <mat-form-field class="filterField"> <mat-select class="filterMultiselect" placeholder="Filter za param3" formControlName="filterParam3" multiple panelClass="filterMultiselect"> <mat-option *ngFor="let option of tableDataSource.data" [value]="option.param3"> {{option.param3}} </mat-option> </mat-select> </mat-form-field> </div> 以及相关组件.ts tableDisplayedColumns: string[] = ['param1', 'param2', 'param3']; columns: any[] = [ { name: 'param1', title: 'Param1' }, { name: 'param2', title: 'Param2' }, { name: 'param3', title: 'Param3' } ]; 为了解决这个问题,我设法通过删除 *ngFor 并手动放入过滤器来做到这一点。 <mat-table class="table" cdkDropList cdkDropListOrientation="horizontal" (cdkDropListDropped)="tableDrop($event)" [dataSource]="tableDataSource"> <ng-container matColumnDef="param1"> <mat-header-cell *matHeaderCellDef cdkDrag cdkDragLockAxis="x" cdkDragBoundary="mat-header-row" [cdkDragStartDelay]="100"> Param1 <mat-form-field class="filterField"> <input matInput type="number" (keydown)="updateManualPage(1)" placeholder="Filter" formControlName="filterParam1"> </mat-form-field> </mat-header-cell> <mat-cell *matCellDef="let data"> <span>{{data.param1}}</span> </mat-cell> </ng-container> <ng-container matColumnDef="param2"> <mat-header-cell *matHeaderCellDef cdkDrag cdkDragLockAxis="x" cdkDragBoundary="mat-header-row" [cdkDragStartDelay]="100"> Param2 <mat-form-field class="filterField"> <input matInput (keydown)="updateManualPage(1)" placeholder="Filter" formControlName="filterParam2" [matAutocomplete]="autoSingleSelect"> <mat-autocomplete #autoSingleSelect="matAutocomplete" class="filterSelect" panelClass="filterSelect"> <mat-option *ngFor="let option of dropdownSingleFilteredOptions | async" [value]="option.param2"> {{option.param2}} </mat-option> </mat-autocomplete> </mat-form-field> </mat-header-cell> <mat-cell *matCellDef="let data"> <span>{{data.param2}}</span> </mat-cell> </ng-container> <ng-container matColumnDef="param3"> <mat-header-cell *matHeaderCellDef cdkDrag cdkDragLockAxis="x" cdkDragBoundary="mat-header-row" [cdkDragStartDelay]="100"> Param3 <mat-form-field class="filterField"> <mat-select class="filterMultiselect" placeholder="Filter" formControlName="filterParam3" multiple panelClass="filterMultiselect"> <mat-option *ngFor="let option of tableDataSource.data" [value]="option.param3"> {{option.param3}} </mat-option> </mat-select> </mat-form-field> </mat-header-cell> <mat-cell *matCellDef="let data"> <span>{{data.param3}}</span> </mat-cell> </ng-container> <mat-header-row class="tableHeader" *matHeaderRowDef="tableDisplayedColumns" #tableHeaderRow> </mat-header-row> <mat-row class="tableRow" *matRowDef="let row; columns: tableDisplayedColumns;" [class.selected-row]="tableSelectedRows.has(row)" (click)="selectUnselectRow(row)"> </mat-row> </mat-table>


活动深层链接 - IllegalArgumentException:缺少必需的参数并且没有 android:defaultValue

在我的应用程序中,我有以下结构: 在我的应用程序中,我具有以下结构: <!-- AndroidManifest.xml --> <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application> <activity android:name=".DeepLinkActivity" android:exported="true" android:launchMode="singleInstancePerTask"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="myhost" android:path="/mypath" android:scheme="myscheme" /> </intent-filter> </activity> </application> </manifest> <!-- activity_deep_link.xml --> <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.fragment.app.FragmentContainerView android:id="@+id/navHostFragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" tools:navGraph="@navigation/my_nav_graph" /> </FrameLayout> // DeepLinkActivity.kt class DeepLinkActivity : AppCompatActivity() { private lateinit var binding: ActivityDeepLinkBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDeepLinkBinding.inflate(layoutInflater) setContentView(binding.root) setUpNavigationGraph() } private fun setUpNavigationGraph() { val navHostFragment = supportFragmentManager .findFragmentById(binding.navHostFragment.id) as NavHostFragment val navController = navHostFragment.navController val navGraph = navController.navInflater .inflate(R.navigation.my_nav_graph) .apply { this.setStartDestination(R.id.notTheStartDestinationFragment) } val startDestinationArgs = bundleOf( "someRequiredArgumentHere" to false ) navController.setGraph(navGraph, startDestinationArgs) } } 当我通过 ADB (adb shell am start -d myscheme://myhost/mypath) 通过深度链接打开该活动时,该活动正常启动。 但是当我通过 Chrome 应用程序启动它时,应用程序崩溃了: 原因:java.lang.IllegalArgumentException:缺少必需参数“someRequiredArgumentHere”并且没有 android:defaultValue 观察:我正在使用 Safe Args 插件。 我做错了什么以及为什么行为不同? 我刚刚发现为什么在通过浏览器导航时会忽略 startDestinationArgs。 如果我们检查NavController#setGraph(NavGraph, Bundle?)的内部代码,如果没有发生深层链接,NavController#onGraphCreated(Bundle?)只会使用startDestinationArgs。 作为一种解决方法,在设置导航图之前,我只需清除活动的意图(但这可能不是解决该问题的最佳方法)


使用 IndexedPointInAreaLocator 和 STRTree(JTS 拓扑套件)无法实现多边形中的点性能

私人列表findZonesForShipPosition(点点){ List zoneDefinitionCacheHits = new ArrayList<>(); strTree.query(point.getEnvelopeIn... private List<ZoneDefinitionCacheMemory> findZonesForShipPosition(Point point) { List<Object> zoneDefinitionCacheHits = new ArrayList<>(); strTree.query(point.getEnvelopeInternal(), zoneDefinitionCacheHits::add); return zoneDefinitionCacheHits.stream() .filter(ZoneDefinitionCacheMemory.class::isInstance) .map(ZoneDefinitionCacheMemory.class::cast) .filter(zoneDefinition -> isPointInsideGeometry(point, zoneDefinition.getGeometry())) .toList(); } private boolean isPointInsideGeometry(Point point, Geometry geometry) { PointOnGeometryLocator pointOnGeometryLocator = new IndexedPointInAreaLocator(geometry); int location = pointOnGeometryLocator.locate(point.getCoordinate()); boolean isInside = location == Location.INTERIOR; return isInside; } 我使用上面的代码来搜索多边形中的点,在查询之前将所有多边形和多边形插入到 strTree 中,并且我还使用 IndexedPointInAreaLocator 在 STR Tree 的顶部添加一个附加过滤器来验证是否给定点是否确实位于几何中。 此外,我的多边形非常大,这意味着某些多边形中有近 160 万个点。 因此,通过此实现,我面临着性能问题,这种方法至少需要 100 毫秒才能完成,这对于我的用例来说是不期望的。 这里可能出现什么问题?或任何以某种方式加快速度的建议。 我的用例:我将获得很多点来检测它们是否位于给定几何形状(多边形和多多边形)的内部或外部 我尝试使用 Polygon.contains(point) 谓词,但它比 IndexedPointInAreaLocator 方法花费更多时间。 如果你的多边形很大(从某种意义上说它们覆盖了很大的区域)或者形状很奇怪。然后,细分它们可能会提高索引性能,请记住索引首先在多边形的边界框上工作,以节省在多边形测试中进行昂贵的点。如果一个点落入许多边界框但只有一个多边形,则索引不会有太大帮助。 Paul Ramsey 的这篇博客文章在 PostGIS 上下文中讨论了这一点,但这里的底层实现是相同的。这个answer将帮助您划分多边形(因为我认为JTS没有细分方法)。 您还可以从 JTS 代码周围使用 GeoTools 中受益,因为这将允许您切换到使用具有内置索引的 PostGIS 或 GeoPackage 数据库,或更简单的 在内存存储中建立索引。


更改垫输入的波纹颜色

我现在一直在努力了解如何手动更改元素的波纹颜色,但我似乎无法让它以任何方式工作。 我现在一直在努力研究如何手动更改 <mat-input> 元素的波纹颜色,但我似乎无法让它以任何方式工作。 <input matInput type="number" (keydown)="updateManualPage(1)" placeholder="Filter" formControlName="filterParam1"> 我已经尝试了CSS中我能想到的一切,.mat-form-field-underline,.mat-form-field-ripple,包括我使用::after和::before选择器从另一个SO问题/答案中无耻地撕掉的一大块类,尝试使用 ::ng-deep、!important,但似乎没有任何东西可以改变从 @import "../node_modules/@angular/material/prebuilt-themes/indigo-pink.css"; 导入的蓝色波纹的颜色 编辑:只需更好地阅读 API,所以我发现波纹后出现的边框颜色来自 <mat-form-field> 元素,该元素有一个颜色选择器。但是,该颜色选择器只能具有“primary”、“accent”和“warn”值。所以现在我想知道如何插入自定义颜色。 设法弄清楚了,原来如此 ::ng-deep .mdc-text-field--filled:not(.mdc-text-field--disabled) .mdc-line-ripple::after { border-bottom-color: *X* !important; }


如何控制列表元素抛出键盘事件

https://stackblitz.com/edit/react-o1ra7c 用户搜索结果后,用户尝试使用键盘事件箭头需要向下移动。 https://stackblitz.com/edit/react-o1ra7c 用户搜索结果后,用户尝试使用键盘事件箭头需要向下移动。 <div> <input onChange={handleSearchChange}/> <div css={countryDataCss}> {countryList?.map((country) => ( <div key={country.countryCode}> <span css={countryCss}>{country.countryName}</span> <span css={countryDialCodeCss}> {country.countryDialNo} </span> </div> ))} </div> </div> 您可以使用 javascirpt 事件 onkeydown,对于 React 来说是 onKeyDown,它提供了所需的行为,请检查下面的 stackblitz! import React from 'react'; import './style.css'; import { useState } from 'react'; export default function App() { const [searchText, setSearchText] = useState(''); const [selectedCountry, setSelectedCountry] = useState('SG'); const [activeIndex, setActiveIndex] = useState(0); const [selectedDialCode, setSelectedDialCode] = useState('+65'); const countryCodeListResponse = [ { countryCode: 'IND', countryDialNo: '+91', countryName: 'India' }, { countryCode: 'SG', countryDialNo: '+65', countryName: 'Singpare' }, ]; const [countryList, setCountryList] = useState(countryCodeListResponse); function handleSearchChange(e) { const searchText = e.target.value.toLowerCase(); if (countryCodeListResponse) { const updatedList = countryCodeListResponse .filter((el) => el.countryName.toLowerCase().includes(searchText)) .sort( (a, b) => a.countryName.toLowerCase().indexOf(searchText) - b.countryName.toLowerCase().indexOf(searchText) ); setSearchText(searchText); setCountryList(updatedList); } } const onSelectCountry = (code, dialCode) => { setSelectedCountry(code); setSelectedDialCode(dialCode); setSearchText(''); setCountryList(countryCodeListResponse); }; const onKeyDown = (event) => { console.log(event); switch (event.keyCode) { case 38: // arrow up if (activeIndex > 0 && activeIndex <= countryList.length - 1) { setActiveIndex((prev) => prev - 1); } break; case 40: // arrow down if (activeIndex >= 0 && activeIndex < countryList.length - 1) { setActiveIndex((prev) => prev + 1); } break; case 13: const country = countryList[activeIndex]; onSelectCountry(country.countryCode, country.countryDialNo); break; default: break; } }; return ( <div class="dropdown"> <div class="search"> <div> <span>{selectedCountry}</span> <span>{selectedDialCode}</span> </div> <input class="search-input" onKeyDown={(e) => onKeyDown(e)} placeholder="Search" value={searchText} onChange={handleSearchChange} /> </div> <div class="list"> {countryList?.map((country, index) => ( <div onKeyDown={(e) => onKeyDown(e)} className={index === activeIndex ? 'active' : ''} tabIndex="0" key={country.countryCode} onClick={() => onSelectCountry(country.countryCode, country.countryDialNo) } > <span>{country.countryName}</span> <span>{country.countryDialNo}</span> </div> ))} </div> </div> ); } 堆栈闪电战


Vue 3如何获取$children的信息

这是我在 Tabs 组件中使用 VUE 2 的旧代码: 创建(){ this.tabs = this.$children; } 标签: .... 这是我在 Tabs 组件中使用 VUE 2 的旧代码: created() { this.tabs = this.$children; } 标签: <Tabs> <Tab title="tab title"> .... </Tab> <Tab title="tab title"> .... </Tab> </Tabs> VUE 3: 如何使用组合 API 获取有关 Tabs 组件中子项的一些信息?获取长度,迭代它们,并创建选项卡标题,...等?有任何想法吗? (使用组合API) 这是我现在的 Vue 3 组件。我使用 Provide 来获取子 Tab 组件中的信息。 <template> <div class="tabs"> <div class="tabs-header"> <div v-for="(tab, index) in tabs" :key="index" @click="selectTab(index)" :class="{'tab-selected': index === selectedIndex}" class="tab" > {{ tab.props.title }} </div> </div> <slot></slot> </div> </template> <script lang="ts"> import {defineComponent, reactive, provide, onMounted, onBeforeMount, toRefs, VNode} from "vue"; interface TabProps { title: string; } export default defineComponent({ name: "Tabs", setup(_, {slots}) { const state = reactive({ selectedIndex: 0, tabs: [] as VNode<TabProps>[], count: 0 }); provide("TabsProvider", state); const selectTab = (i: number) => { state.selectedIndex = i; }; onBeforeMount(() => { if (slots.default) { state.tabs = slots.default().filter((child) => child.type.name === "Tab"); } }); onMounted(() => { selectTab(0); }); return {...toRefs(state), selectTab}; } }); </script> 选项卡组件: <script lang="ts"> export default defineComponent({ name: "Tab", setup() { const index = ref(0); const isActive = ref(false); const tabs = inject("TabsProvider"); watch( () => tabs.selectedIndex, () => { isActive.value = index.value === tabs.selectedIndex; } ); onBeforeMount(() => { index.value = tabs.count; tabs.count++; isActive.value = index.value === tabs.selectedIndex; }); return {index, isActive}; } }); </script> <template> <div class="tab" v-show="isActive"> <slot></slot> </div> </template> 哦伙计们,我解决了: this.$slots.default().filter(child => child.type.name === 'Tab') 对于想要完整代码的人: 标签.vue <template> <div> <div class="tabs"> <ul> <li v-for="tab in tabs" :class="{ 'is-active': tab.isActive }"> <a :href="tab.href" @click="selectTab(tab)">{{ tab.name }}</a> </li> </ul> </div> <div class="tabs-details"> <slot></slot> </div> </div> </template> <script> export default { name: "Tabs", data() { return {tabs: [] }; }, created() { }, methods: { selectTab(selectedTab) { this.tabs.forEach(tab => { tab.isActive = (tab.name == selectedTab.name); }); } } } </script> <style scoped> </style> 标签.vue <template> <div v-show="isActive"><slot></slot></div> </template> <script> export default { name: "Tab", props: { name: { required: true }, selected: { default: false} }, data() { return { isActive: false }; }, computed: { href() { return '#' + this.name.toLowerCase().replace(/ /g, '-'); } }, mounted() { this.isActive = this.selected; }, created() { this.$parent.tabs.push(this); }, } </script> <style scoped> </style> 应用程序.js <template> <Tabs> <Tab :selected="true" :name="'a'"> aa </Tab> <Tab :name="'b'"> bb </Tab> <Tab :name="'c'"> cc </Tab> </Tabs> <template/> 我扫描子元素的解决方案(在对 vue 代码进行大量筛选之后)是这样的。 export function findChildren(parent, matcher) { const found = []; const root = parent.$.subTree; walk(root, child => { if (!matcher || matcher.test(child.$options.name)) { found.push(child); } }); return found; } function walk(vnode, cb) { if (!vnode) return; if (vnode.component) { const proxy = vnode.component.proxy; if (proxy) cb(vnode.component.proxy); walk(vnode.component.subTree, cb); } else if (vnode.shapeFlag & 16) { const vnodes = vnode.children; for (let i = 0; i < vnodes.length; i++) { walk(vnodes[i], cb); } } } 这将返回子组件。我对此的用途是我有一些通用的对话框处理代码,用于搜索子表单元素组件以咨询其有效性状态。 const found = findChildren(this, /^(OSelect|OInput|OInputitems)$/); const invalid = found.filter(input => !input.checkHtml5Validity()); 如果你复制粘贴与我相同的代码 然后只需向“选项卡”组件添加一个创建的方法,该方法将自身添加到其父级的选项卡数组中 created() { this.$parent.tabs.push(this); }, 使用脚本设置语法,您可以使用useSlots:https://vuejs.org/api/sfc-script-setup.html#useslots-useattrs <script setup> import { useSlots, ref, computed } from 'vue'; const props = defineProps({ perPage: { type: Number, required: true, }, }); const slots = useSlots(); const amountToShow = ref(props.perPage); const totalChildrenCount = computed(() => slots.default()[0].children.length); const childrenToShow = computed(() => slots.default()[0].children.slice(0, amountToShow.value)); </script> <template> <component :is="child" v-for="(child, index) in childrenToShow" :key="`show-more-${child.key}-${index}`" ></component> </template> 我对 Ingrid Oberbüchler 的组件做了一个小改进,因为它不支持热重载/动态选项卡。 在 Tab.vue 中: onBeforeMount(() => { // ... }) onBeforeUnmount(() => { tabs.count-- }) 在 Tabs.vue 中: const selectTab = // ... // ... watch( () => state.count, () => { if (slots.default) { state.tabs = slots.default().filter((child) => child.type.name === "Tab") } } ) 我也遇到了同样的问题,在做了很多研究并问自己为什么他们删除了$children之后,我发现他们创建了一个更好、更优雅的替代方案。 这是关于动态组件的。 (<component: is =" currentTabComponent "> </component>). 我在这里找到的信息: https://v3.vuejs.org/guide/component-basics.html#dynamic-components 希望这对你有用,向大家问好!! 我发现这个更新的 Vue3 教程使用 Vue 插槽构建可重用的选项卡组件对于与我相关的解释非常有帮助。 它使用 ref、provide 和ject 来替换我遇到同样问题的this.tabs = this.$children;。 我一直在遵循我最初发现的构建选项卡组件(Vue2)的教程的早期版本创建您自己的可重用 Vue 选项卡组件。 根据 Vue 文档,假设您在 Tabs 组件下有一个默认插槽,您可以直接在模板中访问该插槽的子级,如下所示: // Tabs component <template> <div v-if="$slots && $slots.default && $slots.default()[0]" class="tabs-container"> <button v-for="(tab, index) in getTabs($slots.default()[0].children)" :key="index" :class="{ active: modelValue === index }" @click="$emit('update:model-value', index)" > <span> {{ tab.props.title }} </span> </button> </div> <slot></slot> </template> <script setup> defineProps({ modelValue: Number }) defineEmits(['update:model-value']) const getTabs = tabs => { if (Array.isArray(tabs)) { return tabs.filter(tab => tab.type.name === 'Tab') } else { return [] } </script> <style> ... </style> 并且 Tab 组件可能类似于: // Tab component <template> <div v-show="active"> <slot></slot> </div> </template> <script> export default { name: 'Tab' } </script> <script setup> defineProps({ active: Boolean, title: String }) </script> 实现应类似于以下内容(考虑一组对象,每个部分一个,带有 title 和 component): ... <tabs v-model="active"> <tab v-for="(section, index) in sections" :key="index" :title="section.title" :active="index === active" > <component :is="section.component" ></component> </app-tab> </app-tabs> ... <script setup> import { ref } from 'vue' const active = ref(0) </script> 另一种方法是使用 useSlots,如 Vue 文档(上面的链接)中所述。 在 3.x 中,$children 属性已被删除并且不再受支持。相反,如果您需要访问子组件实例,他们建议使用 $refs。作为数组 https://v3-migration.vuejs.org/writing-changes/children.html#_2-x-syntax 在 3.x 版本中,$children 已被删除且不再受支持。使用 ref 访问子实例。 <script setup> import { ref, onMounted } from 'vue' import ChildComponent from './ChildComponent .vue' const child = ref(null) onMounted(() => { console.log(child.value) // log an instance of <Child /> }) </script> <template> <ChildComponent ref="child" /> </template> 详细信息:https://vuejs.org/guide/essentials/template-refs.html#template-refs 基于@Urkle的回答: /** * walks a node down * @param vnode * @param cb */ export function walk(vnode, cb) { if (!vnode) return; if (vnode.component) { const proxy = vnode.component.proxy; if (proxy) cb(vnode.component.proxy); walk(vnode.component.subTree, cb); } else if (vnode.shapeFlag & 16) { const vnodes = vnode.children; for (let i = 0; i < vnodes.length; i++) { walk(vnodes[i], cb); } } } 除了已接受的答案之外: 而不是 this.$root.$children.forEach(component => {}) 写 walk(this.$root, component => {}) 这就是我让它为我工作的方式。


ng-bootstrap 滚动间谍在没有高度的情况下无法工作?

我在我的项目中使用 ng-bootstrap [ngbScrollSpy] 指令,如文档中所述,但它不起作用 - 滚动时活动项目不会改变。 我的代码如下: 我在我的项目中使用 ng-bootstrap [ngbScrollSpy] 指令,如文档中所述,但它不起作用 - 滚动时活动项目不会改变。 我的代码如下: <div> <div class="sticky-top"> <ul class="nav menu-sidebar"> <li > <a [ngbScrollSpyItem]="[spy, 'about']">About</a> </li> <li > <a [ngbScrollSpyItem]="spy" fragment="schedule">Schedule</a> </li> <li > <a [ngbScrollSpyItem]="spy" fragment="hotel">Information about the hotel</a> </li> </ul> </div> <div ngbScrollSpy #spy="ngbScrollSpy" > <section ngbScrollSpyFragment="about"> <h3>About</h3> <p>{{some long long text and content}}</p> </section> <section ngbScrollSpyFragment="schedule"> <h3>Schedule</h3> <p>{{some long long text and content}}</p> </section> <section ngbScrollSpyFragment="hotel"> <h3>Information about the hotel</h3> <p>{{some long long text and content}}</p> </section> </div> </div> 我在这个 stackoverflow 问题中看到,我的问题是我没有向我的 div 提供 height,这是事实。 但我的滚动间谍部分遍布整个页面,而不是一个小 div,(导航本身是 sticky-top)。所以我不能给它高度。 我知道有替代方法 - 刷新窗口滚动上的滚动间谍,但我没有找到可以帮助我的正确代码。 你能解决我的问题吗? 为我提供刷新滚动间谍的代码/给我有关高度的提示/帮助我找到另一个相应的元素。 非常感谢! 附上 stackblitz 演示的链接 注意:我使用来自 @ng-bootstrap/ng-bootstrap 的 NgbScrollSpy (我想它是非常相似的库) 我做什么: 我将所有内容(包括导航)包装在中 <div class="wrapper" ngbScrollSpy #spy="ngbScrollSpy" rootMargin="2px" [threshold]="1.0" > <div class="sticky-top pt-4 pb-4 bg-white"> ..here the navigation... </div> ..here the sections... <section ngbScrollSpyFragment="about"> </section> //the last I use margin-bottom:2rem; <section ngbScrollSpyFragment="hotel" style="margin-bottom:10rem" </section> </div> 见“门槛”。这表明“更改”活动片段应该可见的百分比(1 是 100%) 包装类 .wrapper{ height:100%; position: absolute; top:0; } 我使用强制链接的类别 //remove all the class for the link a{ color:black; text-decoration:none; padding:8px 16px; } a.custom-active{ color:white; background-color:royalblue } 以及我使用的每个链接 <a [class.custom-active]="spy.active=='about'">About</a> 嗯,问题是如何“滚动到”。 “链接”应该作为链接使用。 第一个是指示“路由器”应该考虑“碎片” 如果我们的组件是独立组件,我们需要使用提供者,provideRouter bootstrapApplication(App, { providers: [ provideRouter([], withInMemoryScrolling({anchorScrolling:'enabled'})), ] }) 然后,我们需要考虑到我们的页面确实没有滚动,div“包装器”是谁拥有滚动。因此,我们订阅 router.events,当事件有“锚点”时,我们滚动“包装器”div constructor(router: Router) { router.events.pipe(filter((e:any) => e.anchor)).subscribe((e: any) => { (document.getElementById('wrapper') as any).scrollTop+= (document.getElementById(e.anchor)?.getBoundingClientRect().top||0) -72; //<--this is the offset }); } 在这个stactblitz中你有一个有效的例子


如何防止点击时嵌套 React 组件中的事件冒泡?

这是一个基本组件。 和 都有 onClick 函数。我只想触发 上的 onClick,而不是 。我怎样才能实现这个目标? 我玩过 这是一个基本组件。 <ul> 和 <li> 都有 onClick 函数。我只想触发 <li> 上的 onClick,而不是 <ul>。我怎样才能实现这个目标? 我尝试过 e.preventDefault()、e.stopPropagation(),但无济于事。 class List extends React.Component { constructor(props) { super(props); } handleClick() { // do something } render() { return ( <ul onClick={(e) => { console.log('parent'); this.handleClick(); }} > <li onClick={(e) => { console.log('child'); // prevent default? prevent propagation? this.handleClick(); }} > </li> </ul> ) } } // => parent // => child 我也有同样的问题。我发现 stopPropagation did 有效。我会将列表项拆分为一个单独的组件,如下所示: class List extends React.Component { handleClick = e => { // do something } render() { return ( <ul onClick={this.handleClick}> <ListItem onClick={this.handleClick}>Item</ListItem> </ul> ) } } class ListItem extends React.Component { handleClick = e => { e.stopPropagation(); // <------ Here is the magic this.props.onClick(); } render() { return ( <li onClick={this.handleClick}> {this.props.children} </li> ) } } React 使用事件委托和文档上的单个事件侦听器来处理冒泡事件,例如本例中的“单击”,这意味着不可能停止传播;当您在 React 中与真实事件交互时,真实事件已经传播。 React 的合成事件上的 stopPropagation 是可能的,因为 React 在内部处理合成事件的传播。 stopPropagation: function(e){ e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); } 关于 DOM 事件的顺序:CAPTURING vs BUBBLING 事件传播有两个阶段。这些被称为 “捕获” 和 “冒泡”。 | | / \ ---------------| |----------------- ---------------| |----------------- | element1 | | | | element1 | | | | -----------| |----------- | | -----------| |----------- | | |element2 \ / | | | |element2 | | | | | ------------------------- | | ------------------------- | | Event CAPTURING | | Event BUBBLING | ----------------------------------- ----------------------------------- 首先发生捕获阶段,然后是冒泡阶段。当您使用常规 DOM api 注册事件时,默认情况下事件将成为冒泡阶段的一部分,但这可以在事件创建时指定 // CAPTURING event button.addEventListener('click', handleClick, true) // BUBBLING events button.addEventListener('click', handleClick, false) button.addEventListener('click', handleClick) 在React中,冒泡事件也是你默认使用的。 // handleClick is a BUBBLING (synthetic) event <button onClick={handleClick}></button> // handleClick is a CAPTURING (synthetic) event <button onClickCapture={handleClick}></button> 让我们看一下handleClick回调(React): function handleClick(e) { // This will prevent any synthetic events from firing after this one e.stopPropagation() } function handleClick(e) { // This will set e.defaultPrevented to true // (for all synthetic events firing after this one) e.preventDefault() } 我在这里没有看到提到的替代方案 如果您在所有事件中调用 e.preventDefault(),您可以检查事件是否已被处理,并防止再次处理它: handleEvent(e) { if (e.defaultPrevented) return // Exits here if event has been handled e.preventDefault() // Perform whatever you need to here. } 关于合成事件和原生事件的区别,请参阅React文档:https://reactjs.org/docs/events.html 这是防止单击事件前进到下一个组件然后调用 yourFunction 的简单方法。 <Button onClick={(e)=> {e.stopPropagation(); yourFunction(someParam)}}>Delete</Button> 这不是 100% 理想,但如果在儿童中传递 props 太痛苦 -> 儿童时尚或为此目的创建 Context.Provider/Context.Consumer just),你正在处理另一个库,它有自己的处理程序,它在您的处理程序之前运行,您也可以尝试: function myHandler(e) { e.persist(); e.nativeEvent.stopImmediatePropagation(); e.stopPropagation(); } 据我了解,event.persist方法可以防止对象立即被扔回React的SyntheticEvent池中。因此,当你伸手去拿 React 中传递的 event 时,它实际上并不存在!这种情况发生在孙子中,因为 React 在内部处理事情的方式是首先检查父进程是否有 SyntheticEvent 处理程序(特别是如果父进程有回调)。 只要您不调用 persist 来创建大量内存以继续创建诸如 onMouseMove 之类的事件(并且您没有创建某种 Cookie Clicker 游戏,例如 Grandma's Cookies),就应该完全没问题! 另请注意:偶尔阅读他们的 GitHub,我们应该密切关注 React 的未来版本,因为他们可能最终会解决一些问题,因为他们似乎打算在编译器中折叠 React 代码/转译器。 如果您希望发生嵌套元素中的操作而不是父元素中的操作,那么,您可以从父元素的操作处理程序中检查目标的类型,然后基于该类型执行操作,即,如果目标是我们的嵌套元素,我们什么也不做。否则两个处理程序都会被调用。 // Handler of the parent element. Let's assume the nested element is a checkbox function handleSingleSelection(e) { if(e.target.type !== 'checkbox') { // We do not do anything from the // parent handler if the target is a checkbox ( our nested element) // Note that the target will always be the nested element dispatch(lineSelectionSingle({ line })) } } 我在 event.stopPropagation() 工作时遇到问题。如果您也这样做,请尝试将其移动到单击处理程序函数的顶部,这就是我需要做的来阻止事件冒泡。示例函数: toggleFilter(e) { e.stopPropagation(); // If moved to the end of the function, will not work let target = e.target; let i = 10; // Sanity breaker while(true) { if (--i === 0) { return; } if (target.classList.contains("filter")) { target.classList.toggle("active"); break; } target = target.parentNode; } } 您可以通过检查事件目标来避免事件冒泡。 例如,如果您将输入嵌套到 div 元素,其中有单击事件的处理程序,并且您不想处理它,则单击输入时,您可以将 event.target 传递到您的处理程序中,并检查处理程序应该是根据目标的属性执行。 例如,您可以检查 if (target.localName === "input") { return}。 所以,这是一种“避免”处理程序执行的方法 解决此问题的另一种方法可能是在子级上设置 onMouseEnter 和 onMouseLeave 事件。 (您的 < li > 标签) 每当鼠标悬停在子级上时,您都可以设置一个特定的状态,以阻止父级执行 onClick 函数内容。 比如: class List extends React.Component { constructor(props) { super(props) this.state.overLi = false } handleClick() { // do something } render() { return ( <ul onClick={(e) => { if (!this.state.overLi) { console.log("parent") this.handleClick() } }} > <li onClick={(e) => { console.log("child") // prevent default? prevent propagation? this.handleClick() }} onMouseEnter={() => this.setState({ overLi: true, }) } onMouseLeave={() => this.setState({ overLi: false, })} ></li> </ul> ) } } 我进行了很多搜索,但没有设法使用 e.stopPropagation() 为我的上下文实现任何解决方案 您可以验证点击的元素是否是预期的元素。 例如: class List extends React.Component { constructor(props) { super(props); } handleClick(e) { if(e.target.className==='class-name'){ // do something } } render() { return ( <ul {/* Replace this with handleClick */} onClick={(e) => { console.log('parent'); this.handleClick(); }} <li onClick={(e) => { console.log('child'); // prevent default? prevent propagation? this.handleClick(); }} </li> </ul> ) } } 执行此操作的新方法更加简单,并且会节省您一些时间!只需将事件传递到原始点击处理程序并调用 preventDefault();。 clickHandler(e){ e.preventDefault(); //Your functionality here }


© www.soinside.com 2019 - 2024. All rights reserved.